Baekjoon Online Judge 1543번 문서 검색 문제

백준 저지 1543번 문서 검색 문제 Pseudo code + Python code

손코딩한 코드에서 논리적 오류를 발견했다. document에서 검색하고자 하는 문자열의 길이만큼 slicing할때, 시작 인덱스(start_index)부터 검색 문자열의 길이(search_word)까지가 아닌, 시작 인덱스(start_index)에서 검색 문자열의 길이(len(search_word))만큼 더한 곳 까지 slicing한 문자열을 비교해야 한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
document = input()
search_word = input()
search_count = 0
start_index = 0

while (len(document)-start_index) // len(search_word) != 0:
# 아래의 조건도 위의 조건을 대체할 수 있다.
# while len(document)-start_index >= len(search_word):
if document[start_index:start_index+len(search_word)] == search_word:
start_index += len(search_word)
search_count += 1
else:
start_index += 1

print(search_count)
Read more