https://www.acmicpc.net/problem/2941
Answer
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
String inputWord = "";
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
inputWord = br.readLine();
} catch (IOException e) {
System.err.println("ERROR : " + e.getMessage());
}
String[] MIXED_ALPHABET_LIST = {"c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="};
for (String MIXED_ALPHABET : MIXED_ALPHABET_LIST) {
while (inputWord.indexOf(MIXED_ALPHABET) != -1) {
inputWord = inputWord.replaceFirst(MIXED_ALPHABET, "A");
}
}
int croatiaWordCount = inputWord.length();
System.out.println(croatiaWordCount);
}
}
Code Review
String inputWord = "";
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
inputWord = br.readLine();
} catch (IOException e) {
System.err.println("ERROR : " + e.getMessage());
}
`try-with-resources`로 try에 자원 객체를 받아서, try 작업이 끝나면 자원을 반환한다.
`System.in`으로 사용자로부터 입력받은 데이터를 바이트 스트림으로 받는다.
`InputStreamReader` 클래스로 바이트 스트림을 문자 기반 스트림으로 변환한다.
`BufferedReader` 클래스로 문자 스트림을 읽는다.
String[] MIXED_ALPHABET_LIST = {"c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="};
for (String MIXED_ALPHABET : MIXED_ALPHABET_LIST) {
while (inputWord.indexOf(MIXED_ALPHABET) != -1) {
inputWord = inputWord.replaceFirst(MIXED_ALPHABET, "A");
}
}
2개 이상의 알파벳이 합쳐진 문자들로 `MIXED_ALPHABET_LIST` 배열을 생성한다.
향상된 for문을 사용하여 `MIXED_ALPHABET_LIST`의 원소값을 하나씩 가져온다.
예를 들어 가져온 원소값 `MIXED_ALPHABET`이 "c="일 경우 while문을 사용하여 `inputWord`에 "c="가 있을 때까지 반복한다.
만약에 'inputWord'가 "c=c="이라면 두 번 반복할 것이다.
`inputWord.indexOf(MIXED_ALPHABET) != -1`는 `inputWord`에서 `MIXED_ALPHABET`이 있다면 해당 위치의 index를 반환하고, 없다면 -1을 반환한다.
즉, 문자열에서 찾고자 하는 단어가 있는지 없는지를 확인한다.
문제 지문을 보면 알파벳 소문자와 '-', '='로만 이루어져 있다고 한다.
즉, 알파벳 대문자로 이루어지지는 않는다는 것이므로 크로아티아 알파벳의 개수를 구하기 위해 A로 변경했다.
만약에 `inputWord`에 "c="가 있다면 `replaceFirst(MIXED_ALPHBET, "A")`로 "c="를 "A"로 변경한 후 다시 `inputWord`에 값을 대입한다.
예를 들어, "c=c="인 경우 "Ac="에서 "AA"가 될 것이다.
`replace(찾을 문자열, 변경할 문자열)` : 문자열에 해당하는 모든 부분을 변경한다.
`replaceAll(정규식, 변경할 문자열)` : 문자열에 정규식으로 해당하는 모든 부분을 변경한다.
`replaceFirst(찾을 문자열, 변경할 문자열)` : 문자열에 해당하는 부분이 여러 개 나오면 첫 번째만 변경한다.
int croatiaWordCount = inputWord.length();
System.out.println(croatiaWordCount);
입력된 단어가 몇 개의 크로아티아 알파벳으로 이루어져 있는지를 구하면 되므로, 반복문을 모두 거쳐 대체된 문자열의 길이만 구하면 된다.
예를 들어, "c=c="인 경우 알파벳으로는 길이가 4이지만 크로아티아 알파벳으로는 길이가 2이다.
따라서 위의 반복문을 거치면 "c=c="에서 "Ac="에서 "AA"가 되므로 최종 길이는 2가 될 것이다.
Result