【Java】SRM 698 DIV2 Easy(250) - Initials

Problem Statement

When dealing with long names and phrases, we sometimes use the initial letters of words to form its acronym. For example, we use "JFK" instead of "John Fitzgerald Kennedy", "lgtm" instead of "looks good to me", and so on.

You are given a String name. This String contains a phrase: one or more words separated by single spaces. Please compute and return the acronym of this phrase. (As above, the acronym should consist of the first letter of each word, in order.)

Definition

  • Class: Initials
  • Method: getInitials
  • Parameters: String
  • Returns: String
  • Method signature: String getInitials(String name) (be sure your method is public)

Limits

  • Time limit (s): 2.000
  • Memory limit (MB): 256
  • Stack limit (MB): 256

Constraints

  • name will contain between 1 and 50 characters, inclusive.
  • Each character in s will be a space or a lowercase English letter ('a' - 'z').
  • The first and last character in s will not be a space.
  • No two continuous spaces can appear in s.

Solution Plan

各フレーズの頭文字を連結しなさいという問題なので、以下の方針でプログラムを記述。

  1. スペース区切りで配列に格納
  2. 1で作成した配列をループし、先頭文字を連結

ある程度Javaのプログラムが書けるのであれば、特に問題なく回答が可能なレベル。

Source Code

public class Initials {

    public String getInitials(String name) {
        String ret = "";
        String[] phrase = name.split(" ");
        for (int i = 0; i < phrase.length; i++) {
            ret += phrase[i].charAt(0);
        }
        return ret;
    }

}