https://www.acmicpc.net/problem/1543
처음에는 간단하게 생각해 문자의 첫번째부터 탐색해 두 번째 문자열과 맞지 않으면 다시 탐색하는 방법을 사용했는데 문제가 틀릴 경우 앞의 문자열에서 다시 탐색을 해야하는 문제가 있어 실패
틀린 코드
#include <iostream>
#include <string>
using namespace std;
int main(void){
ios::sync_with_stdio(false);
cin.tie(NULL);
string s1, s2;
int check = 0;
int cnt = 0;
getline(cin, s1);
getline(cin, s2);
for(int i=0; i<s1.size(); i++){
if(s1[i] == s2[check]){
check++;
} else{
check = 0;
if(s1[i] == s2[check]){
check++;
}
}
if(check == s2.size()){
cnt++;
check=0;
}
}
cout << cnt << '\n';
return 0;
}
그래서 시간은 충분하니 처음부터 끝 문자까지 시작문자로 정해 두 번째 문자열과 비교하였다.
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main(void){
ios::sync_with_stdio(false);
cin.tie(NULL);
string s1, s2;
bool check = true;
int cnt = 0;
stack<char> s;
getline(cin, s1);
getline(cin, s2);
s.push(s1[0]);
for(int i=0; i<(int)s1.size()-(int)s2.size()+1; i++){
for(int j=0; j<s2.size(); j++){
if(s2[j]!=s1[i+j]){
check=false;
break;
}
}
if(check){
cnt++;
i += s2.size()-1;
}
check = true;
}
cout << cnt << '\n';
return 0;
}
주의 사항이 하나 있는데 c++내장함수인 size()는 리턴값이 unsigned long이라 size()끼리의 연산에서 음수가 나올 경우 오버플로우가 난다.