단계별로 풀어보기 > 심화 1 > 그룹 단어 체커
https://www.acmicpc.net/problem/1316
각 문자가 연속해서 나타나는 경우를 그룹 단어라고 칭할 때, N개의 단어를 입력 받을 때, 그룹 단어인 갯수를 출력하라.

flag는 그룹 단어 인 경우 true, diffch는 하나의 문자를 기준으로 다른 문자가 나왔을 때 true로 변경 될 수 있도록 한다.
이 때, 다른 문자가 나온 상태에서 비교대상 문자와 순회중인 문자가 같은 경우 그룹단어가 아니기 때문에 flag를 true로 변경한다.
import java.io.*;
public class 그룹_단어_체커 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int N = Integer.parseInt(br.readLine());
int count = 0;
for(int i = 0; i < N; i++){
String str = br.readLine();
boolean flag = false;
for(int j = 0; j < str.length()-1; j++){
boolean diffch = false;
char ch = str.charAt(j);
for(int l = j+1; l < str.length(); l++){
if(diffch == true && str.charAt(j) == str.charAt(l)){
flag = true;
}
if(diffch == false && str.charAt(j) != str.charAt(l)){
diffch = true;
ch = str.charAt(l);
}
}
}
if(!flag) count++;
}
bw.write(String.valueOf(count));
bw.flush();
bw.close();
br.close();
}
}
해당 코드의 시간복잡도는 단어의 평균 길이를 n이라 두었을 때, O(n^2)의 시간 복잡도를 가지게 된다.
이유는 단어의 길이 만큼 for(j) 를 돌고, 단어의 길이 -1 만큼 for(l)을 돌기 때문이다.
