
스택으로 풀었지만, 스택으로 size()를 사용하면 O(n) 시간 복잡도가 사용된다.
이에 따라 그냥 int 값으로 저장하면 O(1)로 줄어드니 그게 더 효율적인 것 같다.
효율적인 방법은 후자지만, 막상 시험때는 잘 생각나지 않을 수도..?
스택 풀이법 1
#include <iostream>
#include <stack>
#define endl "\n"
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
stack<char> stack;
int result = 0;
char c;
char before = '\0';
while(cin.get(c)) {
if (c == '(') {
stack.push(c);
} else if (c == ')') {
stack.pop();
result += (before == '('? stack.size() : 1);
}
before = c;
}
cout << result << endl;
}
int 변수값 풀이법 2
#include <iostream>
#define endl "\n"
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int result = 0;
int openCnt = 0;
char c;
char before = '\0';
while(cin.get(c)) {
if (c == '(') {
openCnt++;
} else if (c == ')') {
openCnt--;
result += (before == '('? openCnt : 1);
}
before = c;
}
cout << result << endl;
}'Algorithm > BOJ' 카테고리의 다른 글
| [백준] 2623번 Gold 3 음악프로그램, C++ (0) | 2025.12.14 |
|---|---|
| [백준] 2524번 Gold 5 괄호의 값, C++ 코드 (0) | 2025.12.12 |
| [백준] 11003번 Gold 1 최솟값 찾기, C++ 코드 (0) | 2025.12.11 |
| [백준] 18258번 Silver 4 큐 2, C++ 코드 (0) | 2025.12.11 |
| [백준] 1021번 Silver3 회전하는 큐, C++ 코드 (0) | 2025.12.10 |