본문 바로가기

■ 알고리즘 문제 풀이/SWEA

[SWEA-D3] 1213. String

▶문제설명

[SWEA] 1213. String

https://www.swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV14P0c6AAUCFAYi&categoryId=AV14P0c6AAUCFAYi&categoryType=CODE


▶Hint


패턴 매칭 알고리즘을 활용한다.



▶Solution


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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include<iostream>
#include<string>
using namespace std;
 
string str, pattern;
int patternLen;
int strLen;
 
int getJumpSize(int idxS, int idxP) {
    int jump = 0, idx = 0;
    char ch = 0;
    
    while (true
    {
        if (str[idxS] == pattern[idxP]) {
            if (idxP == 0)
                return -1;
 
            idxS--;
            idxP--;
 
            continue;
        }
 
        ch = str[idxS];
        if ((idx = pattern.substr(0,idxP).find(ch)) != string::npos) { // 패턴내에 문자가 존재하는경우
            jump = (patternLen - 1- idx;
        }
        else
            jump = patternLen;
 
        break;
    }
 
    return jump;
}
 
int main(int argc, char** argv)
{
    int T, idxS, idxP, jump, answer;
 
    for (int test_case = 0; test_case < 10; test_case++) {
        cin >> T;
        cin >> pattern;
        cin >> str;
 
        patternLen = pattern.length();
        strLen = str.length();
        idxS = idxP = pattern.length() - 1;
        answer = jump = 0;
 
        while (true
        {
            jump = getJumpSize(idxS, idxP);
        
            if (jump == -1) {
                answer++;
                jump = pattern.length();
            }
 
            idxS += jump;
 
            if (strLen - 1 < idxS)
                break;
        }
        printf("#%d %d\n", T, answer);
    }
 
    return 0;
}
 
 
cs



'■ 알고리즘 문제 풀이 > SWEA' 카테고리의 다른 글

[SWEA] 6808. 규영이와 인영이의 카드게임  (0) 2019.03.02
[SWEA] 5653. 줄기세포배양  (0) 2019.02.26
[SWEA-D4] 1211. Ladder2  (0) 2019.02.20
[SWEA-D4] 1210. Ladder1  (0) 2019.02.20
[SWEA-D3] 1209. Sum  (0) 2019.02.20