본문 바로가기
CS(Computer Science)지식/[C++][코딩 테스트] 자료구조 및 알고리즘

[C++] 백준 1543번: 문서 검색

by 엔지니어 청년 2024. 2. 4.

문제링크

https://www.acmicpc.net/problem/1543

풀이방법

String STL을 사용하여 쉽게 해결 할 수 있다.

찾고 하는 문자열을 찾은 뒤에는 그 문자열 이후 문자열부터 다시 찾는 방식으로 개수를 세어나가면 정답을 구할 수 있다. 특히 string STL 에 내장되어있는 find 함수를 사용하면 더욱 쉽게 해결할 수 있다.

String 객체에 대해서 잘 모른다면 아래 영상을 참고하자

코드

#include <bits/stdc++.h>
using namespace std;


int pos = 0;

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	string t;
	string p;
	getline(cin, t);
	getline(cin, p);
	int cnt = 0;
	int f = t.find(p);
	while (f != string::npos) // npos == -1
	{
		cnt++;
		f = t.find(p, f + p.size());
	}
	cout << cnt << '\n';

}