[알고리즘/자바] 백준 1316번 - 그룹 단어 체커

2021. 7. 27. 08:10개발/알고리즘

 

1316번: 그룹 단어 체커

그룹 단어란 단어에 존재하는 모든 문자에 대해서, 각 문자가 연속해서 나타나는 경우만을 말한다. 예를 들면, ccazzzzbb는 c, a, z, b가 모두 연속해서 나타나고, kin도 k, i, n이 연속해서 나타나기 때

www.acmicpc.net

입력된 문자에 존재하는 알파벳이 연속되는지 확인하는 문제이다. 

 

 

아이디어


1. 입력된 문자에 존재하는 알파벳을 구한다.

2. 알파벳이 연속되는지 확인한다. 

3. 현재의 index가 이전의 index보다 +1인 경우는 연속이며 그렇지 않은 경우는 불연속이다.

4. 문자내에 알파벳이 하나만 있는 경우는 연속으로 처리한다.

 

 

구현


getAlphabet 함수를 만들어 입력된 문자내에 존재하는 알파벳을 ArrayList로 반환하도록 한다.

solve 함수에서 그룹단어인지 확인한다. 

indexOf 함수의 2번째 파라미터는 검색의 시작위치를 뜻한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
 
public class Main {
    
    // word에 존재하는 알파벳을 반환한다.
    public static ArrayList<Character> getAlphabet(String word) {
        
        ArrayList<Character> alphabets = new ArrayList<Character>();
        for(int i=0; i<word.length(); i++) {
            if(!alphabets.contains(word.charAt(i))) {
                alphabets.add(word.charAt(i));
            }
            
        }
        return alphabets;
        
    }
    
    // word가 그룹단어면 true를 리턴한한다.
    public static boolean solve(String word) {
        
        ArrayList<Character> alphabets = getAlphabet(word);
        // 알파벳을 순회한다.
        for(int i=0; i<alphabets.size(); i++) {
            
            int index = word.indexOf(alphabets.get(i));
            while(true) {
                
                // 문자가 하나뿐인경우는 수행할 필요 없음
                if(word.indexOf(alphabets.get(i),index + 1== -1break;
                
                //다음번 알파벳의 위치가 현재보다 +1인 경우는 연속이다. 
                if(index + 1 == word.indexOf(alphabets.get(i),index + 1) ) {
                    // 현재 위치를 update 한다.
                    index = word.indexOf(alphabets.get(i),index + 1);
                } else {
                    return false;
                }
                
            }
        }
        return true;
    }
    
    
    
    
    public static void main(String[] args) throws IOException{
        // 입력
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); //선언
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));//선언
        
        int result = 0;
        int inputCase = Integer.valueOf(bf.readLine()); //String
        for(int i=0; i<inputCase; i++) {
            String word = bf.readLine();
            if(solve(word)) result++;
            
        }
        
        bw.write(result + "\n");
        
        bw.flush();//남아있는 데이터를 모두 출력시킴
        bw.close();//스트림을 닫음
        
        
    }
    
}
cs