1786 찾기

2019. 9. 25. 21:12알고리즘/백준

KMP 기본문제로 패턴에 대한 실패 배열을 만들어서, 이를 이용해 중복 검사를 피할 수 있다

 

문제: https://www.acmicpc.net/problem/1786

깃허브주소: https://github.com/surinoel/boj/blob/master/1786.cpp

 

#include <cstdio>
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
using namespace std;
vector<int> makeTable(string pattern) {
int strsize = pattern.size();
vector<int> table(strsize);
int j = 0;
for(int i=1; i<strsize; i++) {
while(j > 0 && pattern[i] != pattern[j]) {
j = table[j-1];
}
if(pattern[i] == pattern[j]) {
table[i] = ++j;
}
}
return table;
}
void KMP(string parent, string pattern) {
int prsize = parent.size();
int ptsize = pattern.size();
int j = 0;
vector<int> table = makeTable(pattern);
vector<int> ans;
for(int i=0; i<prsize; i++) {
while(j > 0 && parent[i] != pattern[j]) {
j = table[j-1];
}
if(parent[i] == pattern[j]) {
if(j == ptsize-1) {
ans.push_back(i-ptsize+2);
j = table[j];
}
else {
j++;
}
}
}
cout << ans.size() << '\n';
for(int i=0; i<ans.size(); i++) {
cout << ans[i] << '\n';
}
}
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(0);
string parent, pattern;
getline(cin, parent);
getline(cin, pattern);
KMP(parent, pattern);
return 0;
}
view raw 1786.cpp hosted with ❤ by GitHub

'알고리즘 > 백준' 카테고리의 다른 글

16637 괄호 추가하기  (0) 2019.09.27
1305 광고  (0) 2019.09.26
16927 배열 돌리기 2  (0) 2019.09.24
1463 1로 만들기  (0) 2019.09.22
17471 게리맨더링  (0) 2019.09.21