반응형
Notice
Recent Posts
Recent Comments
Link
«   2025/06   »
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
Tags
more
Archives
Today
Total
관리 메뉴

배움과 기록의 장

[백준] 1316번: 그룹 단어 체커 (Java) 본문

problem solving

[백준] 1316번: 그룹 단어 체커 (Java)

chaeunii 2023. 3. 9. 22:42

✅ 문제

https://www.acmicpc.net/problem/1316

 

✅ 풀이

  • String 타입의 reducedStr를 만들어서, 연속하는 중복 문자를 제외하고 담아준다.
    • 앞,뒤문자 비교해서다르면 reducedStr에 넣어주기 ex) aabbbcca -> abca
  •  reducedStr에 중복하는 문자가 있으면 그룹단어가 아니고, 없으면 그룹단어이다 
    • 첫문자와 나머지문자들로 쪼개서 나머지문자들에 첫문자가 포함되어있는지 확인, 있으면 그룹단어 x 없으면 나머지문자가 하나 남을 때까지 반복 (두개 남을 때까지 해도 된다. 어차피 남은 두개가 다른 건 명확하니까)
      ex) abca -> a, bca 쪼갬 -> bca에 a 포함되어있음 -> 그룹단어 x
  •  
  • substring(int beginIndex) 에 대해
    • "emptiness".substring(9) 은 예외가 아닌 "" 빈 스트링을 반환한다. (beginIndex가 문자열 길이와 같을 경우)
    • beginIndex가 음수이거나 문자열의 길이보다 클 경우, IndexOutOfBoundsException 를 던진다

 

✅ 코드

import java.util.Scanner;

public class Main{
    public static void main(String[] args){

        Scanner sc = new Scanner(System.in);
        int num = Integer.parseInt(sc.nextLine());

        int count = 0;
        for(int i = 0; i < (int)num; i++){
            String str = sc.nextLine();

            // str에서 연속하는 중복문자는 제외하고 새로 담는다.
            String reducedStr = "" + str.charAt(0);
            for(int j = 1; j < str.length(); j++){
                if(str.charAt(j-1) != str.charAt(j)) reducedStr += str.charAt(j);
            }

            // reducedStr에서 중복하는 문자가 있으면 그룹단어 x 없으면 그룹단어 ㅇ
            boolean isGroupWord = true;
            while(reducedStr.length()>1){
                String temp = "" + reducedStr.charAt(0);
                reducedStr = reducedStr.substring(1);
                if(reducedStr.contains(temp)){
                    isGroupWord = false;
                    break;
                }
            }

            if(isGroupWord) count++;
        }
        System.out.println(count);
    }
}

 

 

 

반응형