반응형

문제 출처 :

 

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


알고리즘 분석 :


문제 해결에 필요한 사항

1. 단어 및 문장 검색 방법

2. strstr 함수 활용법

2. 중복되지 않도록 검색하는 방법


strstr함수는 strstr(문자열, 찾고자하는 단어 및 문장);으로 구성되어 있으며


검색을 성공할 시 그 시작위치를 반환하고 검색에 실패할 시 NULL을 반환한다.


gets로 받은 이유는 공백을 scanf로는 포함할 수 없기에 gets로 받아들인다.


그리고, while문 내부 해석은


strstr(pos, find)가 존재한다면 while이 진행되고


strstr로 찾아낸 위치를 pos에 저장, 그리고 pos값은 pos + 그 단어 혹은 문장 길이를 해준다.


예를들어 abcabc이고 찾고자 하는 단어가 abc이면


처음 pos = strstr(pos, find)에 의해 첫번째 a위치가 반환된다.


그다음 pos = pos + strlen(find)에 의해 abcabc의 굵은 a위치로 pos가 이동한다. 


이 작업을 문서 내용이 끝날 때 까지 반복한다.



소스 코드 : 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <stdio.h>
 
int main()
{
    char arr[2501];
    char find[51];
    char *pos;
    int cnt = 0;
 
    gets(arr);
    gets(find);
 
    pos = arr;
    while (strstr(pos, find) != NULL)
    {
        pos = strstr(pos, find);
        pos = pos + strlen(find);
        cnt++;
    }
 
    printf("%d", cnt);
 
    return 0;
}
 
 
//                                                       This source code Copyright belongs to Crocus
//                                                        If you want to see more? click here >>
Crocus


반응형