Problem B 풀이 (C++)

 문제 링크 : https://codeforces.com/contest/1547/problem/B

입력받은 문자열 str에서 a의 위치를 찾는다. ( a가 없다면 no 출력. )

a가 있는데 문자열의 길이가 1이라면 yes 출력.

alphabetical 인지를 확인하기 위해 문자 a에 b ~ z까지 차례대로 문자열의 양옆을 확인해 나간다.

계산을 위해 front와 back 변수를 사용한다. front와 back의 초기값은 a의 index 값이다.

다음 b가 문자열에 적절하게 포함되어 있는지 확인하기 위해 

str[front - 1]의 문자와 str[back + 1]의 문자를 확인하여 b가 있는지 확인 후 b가 a의 앞부분에 있다면 front--, 뒷부분에 있다면 back++ 해준다.

같은 방법으로 z까지 확인한다.

문자열 길이까지 모두 확인했다면 yes 출력.

도중에 문자가 확인이 안되면 no 출력.


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
#include <iostream>
 
using namespace std;
 
int main() {
 
    int t;
    cin >> t;
 
    while (t--) {
 
        string s;
        cin >> s;
 
        int front = -1, back = -1;
        string str = "";
        char alpha = 'b';
 
        for (int i = 0; i < s.length(); i++) {
            if (s[i] == 'a') {
                front = back = i;
                str += 'a';
                break;
            }
        }
 
        if (front == -1) {
            cout << "NO" << endl;
            continue;
        }
 
        if (back - front + 1 == s.length()) {
            cout << "YES" << endl;
            continue;
        }
 
        while (alpha <= 'z') {
 
            bool isPut = false;
 
            if (front > 0 && s[front - 1== alpha) {
                front--;
                isPut = true;
            }
            else if (back < s.length() - 1 && s[back + 1== alpha) {
                back++;
                isPut = true;
            }
 
            if (isPut == false) {
                cout << "NO" << endl;
                break;
            }
            else if (back - front + 1 == s.length()) {
                cout << "YES" << endl;
                break;
            }
 
            alpha++;
        }
 
    }
 
    return 0;
}
cs

댓글