https://www.acmicpc.net/problem/1316
Answer
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
int wordCount = 0;
int groupWordCheckerCount = 0;
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
wordCount = Integer.parseInt(br.readLine());
for (int i = 0; i < wordCount; i++) {
groupWordCheckerCount += checkGroupWord(br.readLine()) ? 1 : 0;
}
} catch (IOException e) {
System.err.println("ERROR : " + e.getMessage());
}
System.out.println(groupWordCheckerCount);
}
static boolean checkGroupWord(String word) {
final int ALPHABET_COUNT = 26;
final int LOWERCASE_A_DECIMAL = 97;
boolean[] alphabetCheckList = new boolean[ALPHABET_COUNT];
int alphabetIndex = -1;
char prevChar = 'A';
for (char nowChar : word.toCharArray()) {
if (nowChar != prevChar) {
alphabetIndex = nowChar - LOWERCASE_A_DECIMAL;
if (alphabetCheckList[alphabetIndex]) {
return false;
} else {
alphabetCheckList[alphabetIndex] = true;
prevChar = nowChar;
}
}
}
return true;
}
}
Code Review
int wordCount = 0;
int groupWordCheckerCount = 0;
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
wordCount = Integer.parseInt(br.readLine());
for (int i = 0; i < wordCount; i++) {
groupWordCheckerCount += checkGroupWord(br.readLine()) ? 1 : 0;
}
} catch (IOException e) {
System.err.println("ERROR : " + e.getMessage());
}
`try-with-resources`로 try에 객체의 자원을 받아서, try 작업이 끝나면 자원을 반환한다.
`System.in`으로 사용자로부터 입력받은 데이터를 바이트 스트림으로 받는다.
`InputStreamReader` 클래스로 바이트 스트림을 문자 기반 스트림으로 변환한다.
`BufferedReader` 클래스로 문자 스트림을 읽는다.
첫째 줄에 입력받는 단어의 개수를 `wordCount` 변수에 대입하고, 이 변수를 활용하여 반복문을 돌린다.
`checkGroupWord()` 메서드에서 그룹 단어인지 체크하여 boolean 함수로 true 또는 false를 반환받는다.
이를 통해 `checkGroupWord(br.readLine()) ? 1 : 0`삼항연산자로 true이면 1, false이면 0인 반환값을 그룹 단어인 단어 수 `groupWordCheckerCount`에 더한다.
final int ALPHABET_COUNT = 26;
final int LOWERCASE_A_DECIMAL = 97;
boolean[] alphabetCheckList = new boolean[ALPHABET_COUNT];
int alphabetIndex = -1;
char prevChar = 'A';
알파벳의 소문자의 개수는 "26", 소문자 a의 10진수는 "97"이므로 상수로 변수를 선언했다.
26개의 소문자를 체크하기 위해 `boolean` 배열을 선언했다.
index는 0부터 시작하기 때문에 `alphabetIndex`의 초깃값을 "-1"로 선언했다.
지문에서 소문자로 입력을 받기 때문에 `prevChar`의 초깃값을 "A"로 선언했다.
for (char nowChar : word.toCharArray()) {
if (nowChar != prevChar) {
alphabetIndex = nowChar - LOWERCASE_A_DECIMAL;
if (alphabetCheckList[alphabetIndex]) {
return false;
} else {
alphabetCheckList[alphabetIndex] = true;
prevChar = nowChar;
}
}
}
return true;
향상된 for문으로 단어의 문자 하나씩 아래 로직을 반복한다.
`nowChar != prevChar`는 현재 문자가 이전 문자와 다르다는 뜻이니
index를 구하기 위해 `nowChar - LOWERCASE_A_DECIMAL`로 계산하여 현재 문자가 나온적이 있는지 index로 `alphabetCheckList`를 확인한다.
`alphabetCheckList[alphabetIndex]`를 확인하여 true면 나왔던 문자이므로 그룹 단어가 아님을 false로 반환하고, false면 나오지 않았던 문자이므로 `alphabetCheckList[alphabetIndex]`을 true를 대입 후 현재 문자를 이전 문자로 변경한다.
반복문 안에서 return되지 않았다면 그룹 단어로써 통과한 것이니 true를 반환한다.
Result