stackCount
를 사용해서 '('
의 경우에는 count
가 1 증가하고 ')'
는 1 감소하도록 했다. stackCount
가 결론적으로 0이 나오면 제대로 실행이 된다는 것, 하지만 예외의 경우가 존재했다.
⭐️ ())(()
: 이 경우에는 결론적으로 0이 나오지만 잘못된 괄호라고 볼 수 있다.
#include <iostream>
#include <string>
using namespace std;
int main() {
int caseNumber = 0, caseCount = 0;
cin >> caseNumber;
while(1) {
if(caseCount == caseNumber) break;
else caseCount++;
int stackCount = 0;
string parenthesis;
cin >> parenthesis;
for(int i = 0; i < parenthesis.length(); i++){
if(parenthesis[i] == '(') stackCount++;
else stackCount--;
}
if(stackCount == 0) cout << "YES" << endl;
else cout << "NO" << endl;
}
}
이번에는 stack
이라는 배열을 만들어서 '('
가 나올 때 넣어주고 아닐 땐 빼주는 식의 stack
의 역할을 하도록 했다. 아까 코드와는 다르게 제대로 된 결과를 내보냈다.
#include <iostream>
#include <string>
using namespace std;
int main() {
int caseNumber = 0, caseCount = 0;
cin >> caseNumber;
while(1) {
if(caseCount == caseNumber) break;
else caseCount++;
int stackCount = 0;
bool isVaild = true;
char stack[50];
string parenthesis;
cin >> parenthesis;
for(int i = 0; i < parenthesis.length(); i++){
if(parenthesis[i] == '('){
stack[stackCount++] = parenthesis[i];
}
else if(parenthesis[i] == ')' && stackCount != 0)
stack[stackCount--] = '\0';
else if(parenthesis[i] == ')' && stackCount == 0) {
isVaild = false;
break;
}
}
if(stackCount != 0) isVaild = false;
if(isVaild) cout << "YES" << endl;
else cout << "NO" << endl;
}
}
stack
를 사용하는 방법인데, 위의 식보다 코드를 이해하기 쉽다는 장점이 있는 거 같다. 실제 stack
에서 사용하는 push
, pop
, empty
를 따로 함수로 구현하지 않아도 사용할 수 있다. 해당 코드도 제대로 된 결과를 냈다. 걸린 시간은 위의 코드와 동일했다.
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool parenCheck(string parenthesis){
stack<char> parenStack;
for(int i = 0; i < parenthesis.length(); i++){
char c = parenthesis[i];
if(c == '(')
parenStack.push(parenthesis[i]);
else if(c == ')' && !parenStack.empty())
parenStack.pop();
else if(c == ')' && parenStack.empty())
return false;
}
if(parenStack.empty()) return true;
else return false;
}
int main() {
int caseNumber = 0, caseCount = 0;
cin >> caseNumber;
while(1) {
if(caseCount == caseNumber) break;
else caseCount++;
string parenthesis;
cin >> parenthesis;
if(parenCheck(parenthesis)) cout << "YES" << endl;
else cout << "NO" << endl;
}
}