Home 6550번(부분 문자열)
Post
Cancel

6550번(부분 문자열)

첫 시도

  • 별다른 알고리즘이 필요 없는 문제
  • 찾아야 하는 단어를 한글자씩 탐색, 문자열이 끝날때까지 다 찾는다면 Yes, 못찾는다면 NO를 반환할 것
  • while(true)로 하면 런타임 에러(NullPointer)가 발생하므로 입력받은 문자열이 Null 인지 확인해야 함

해결

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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    static String str;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        while((str = br.readLine()) != null){ // nullpoint error용
            String[] input = str.split(" ");
            String goal = input[0]; // 목표 문자열
            String compare = input[1]; // 비교 문자열
            int index = 0; // goal 배열에 인덱스 변수
            boolean flag = false; // 목표 문자열을 만들 수 있는지 확인용

            for(int i = 0; i < compare.length(); i++){ // 비교 문자열 만큼 반복
                char alpa = compare.charAt(i);
                if(goal.charAt(index) == alpa){ // 비교 문자열에서 목표 알파벳을 찾았으면
                    index++;
                }
                if(index == goal.length()){ // 목표 문자열을 다 찾으면
                    flag = true;
                    break;
                }
            }
            if(flag) System.out.println("Yes");
            else System.out.println("No");
        }

    }
}

참고

  • 직접구현
This post is licensed under CC BY 4.0 by the author.