알고리즘

[알고리즘 / 백준] 1543 - 문서 검색

DevBee 2020. 11. 13. 09:18

 

문제는 위와 같으며 최대 문서의 길이가 2500 이고, 검색하고 싶은 단어의 최대 길이가 50 이므로 처음부터 순서대로 모든 경우를 검색하여 문제를 해결할 수 있습니다.

 

파이썬 코드는 다음과 같습니다.

from sys import stdin

string = stdin.readline().strip()
search = stdin.readline().strip()

count = 0
find_idx = 0
while find_idx <= len(string) - len(search):
    if string[find_idx:find_idx + len(search)] == search:
        count += 1
        find_idx += len(search) + 1
    else:
        find_idx += 1

print(count)

 

자바 코드는 다음과 같습니다.

import java.io.BufferedReader;
import java.io.InputStreamReader;

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

        String string = br.readLine();
        String word = br.readLine();

        int count = 0;
        int findIdx = 0;

        while (string.length() - word.length() >= findIdx) {
            if (string.substring(findIdx, findIdx + word.length()).equals(word)) {
                count += 1;
                findIdx += word.length();
            } else {
                findIdx += 1;
            }
        }

        System.out.println(count);
    }
}