SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
<풀이>
1. 괄호 문자열을 입력받는다.
2. 괄호들의 짝이 모두 맞는지 출력한다.
<해법>
1. 괄호들이 짝이 맞는지 판단하는 방법
=> 스택을 사용합니다. '({[' 이렇게 나왔다면, 뒤에는 ']})' 이렇게 나와야합니다. 따라서, 스택의 연산(push, pop)으로 자연스럽게 괄호의 짝을 알아볼 수 있습니다.
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
|
#include <iostream>
#include <stack>
using namespace std;
int length;
string str;
bool answer;
bool isPair(char left, char right) {
if (left == '(' && right == ')') return true;
else if (left == '[' && right == ']') return true;
else if (left == '{' && right == '}') return true;
else if (left == '<' && right == '>') return true;
return false;
}
bool isValid(string str) {
stack<char> s;
for (int i = 0; i < length; i++) {
char c = str[i];
if (c == '(' || c == '[' || c == '{' || c == '<') {
s.push(c);
}
else {
if (isPair(s.top(), c)) s.pop();
else return false;
}
}
if (!s.empty()) return false;
return true;
}
void solution() {
answer = isValid(str);
}
int main() {
int test_case;
int T;
T = 10;
for (test_case = 1; test_case <= T; test_case++) {
//초기화
length = 0;
str = "";
answer = false;
//입력
cin >> length >> str;
//해법
solution();
//출력
cout << "#" << test_case << " " << answer << "\n";
}
//종료
return 0;
}
|
자료구조 스택에 대해 알아볼 수 있는 문제였습니다.
'알고리즘 문제풀이 > SWEA' 카테고리의 다른 글
[C++] SWEA 1224 - 계산기3 (0) | 2022.12.21 |
---|---|
[C++] SWEA 1219 - 길찾기(2) (0) | 2022.12.21 |
[C++] SWEA 2117 - 홈 방범 서비스(2) (1) | 2022.12.21 |
[C++] SWEA 1217 - 거듭 제곱 (0) | 2022.12.21 |
[C++] SWEA 1216 - 회문2 (0) | 2022.12.15 |