[백준 Deepening] 1316번 문제

Kwon·2023년 11월 22일

백준

목록 보기
14/22
post-thumbnail

백준 1316번 문제

풀이

  • 그룹 단어를 찾는 문제. 예를 들어 aabbc 혹은 abc는 한 글자 씩 연속 단어이기에 그룹 단어, 하지만 aabca 는 a가 비 연속적이기에 그룹 단어가 아님
  • 한 단어에 각 알파벳이 연속인지 비연속인지 확인해야 하는 문제
  • for문과 if문을 잘 조화롭게 사용하면 해결 가능. (조금 까다로운 문제였음)
import java.util.Scanner;

public class deepening7 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        boolean continuous = true;
        boolean uncontinuous = false;
         // 이미 연속했던 단어는 lock해버리자
        int N = sc.nextInt(); String[] word = new String[N];
        for (int i = 0; i < N; i++) {
            word[i] = sc.next();
        }
        int result = 0;

        for (String wordCheck:word) {
            for (int i = 0; i < wordCheck.length(); i++) {
                continuous = true;
                uncontinuous = false;
                for (int j = i; j < wordCheck.length(); j++) {
                    if (i==j) continue;
                    if (wordCheck.charAt(i) == wordCheck.charAt(j)) {
                        if(uncontinuous) continuous = false;}
                    else if(wordCheck.charAt(i) != wordCheck.charAt(j)) uncontinuous = true;
                }
                if(!continuous) break;
            }
            if(continuous) result++;
        }
        System.out.println(result);
    }
}

풀이

1. 연속 및 비연속 설정

boolean continuous = true;
boolean uncontinuous = false;
  • continuous는 연속적인 알파벳 확인을 위해 설정
  • uncontinuous는 비연속적인 알파벳 확인을 위해 설정

2. 갯수 및 단어 입력

int N = sc.nextInt(); String[] word = new String[N];
for (int i = 0; i < N; i++) {
    word[i] = sc.next();
}
int result = 0;

입력 할 단어 개수 설정 그리고 그룹 단어 수 확인을 위해 result 변수 설정

3. 그룹 단어 확인

for (String wordCheck:word) {
    for (int i = 0; i < wordCheck.length(); i++) {
        continuous = true;
        uncontinuous = false;
        for (int j = i; j < wordCheck.length(); j++) {
            if (i==j) continue;
            if (wordCheck.charAt(i) == wordCheck.charAt(j)) {
                if(uncontinuous) continuous = false;}
            else if(wordCheck.charAt(i) != wordCheck.charAt(j)) uncontinuous = true;
        }
        if(!continuous) break;
    }
    if(continuous) result++;
}

for

  • 첫 for문은 입력 받았던 단어 하나씩 검사하기 위해 for each문을 이용했다.
  • 두 번째 for문은 단어 한 알파벳을 기준을 잡고 세 번째 for문에서 그룹 단어를 검사한다.

if

  • 첫 번째 if문은 자기 자신을 검사할 시 continue
  • 두 번째 if문에선 기준 잡은 알파벳 뒤의 알파벳이 같은 알파벳인지 확인한다. 다른 알파벳이 등장 시, else if문으로 빠짐(비연속 단어 확인 부분).
  • 만일 연속적 알파벳 검사 후 비연속적 알파벳 검사하다 다시 연속적 알파벳 등장 시 uncontinuous가 true이기 때문에 그룹 단어가 아니게 되므로 continuous를 false로 반환.
  • 그리고 continuous가 false이면 그룹 단어에서 배제 되므로 바로 break

profile
📲 @bu_kwon_2 / 💻 dnu05043.log / ⌨ Back-end / 🦁 LikeLion

0개의 댓글