1. JavaScript
정해
function solution(S) {
let stack = [];
for(let i=0; i<S.length; i++){
if(S.charAt(i) == '('){
stack.push(i);
}
if(S.charAt(i) == ')'){
if(stack.length > 0){
stack.pop();
}
else{
return 0;
}
}
}
return stack.length == 0 ? 1 : 0
}
87%
function solution(S) {
const list = Array.from(S);
let stack = [];
for (char of list){
if(char == '('){
stack.push(char);
}else if(stack.length == 0 || stack.pop() != '('){
return 0
}
}
return stack.length == 0 ? 1 : 0
}
2. Python
def solution(S):
if len(S) == 0: return 1
if len(S) == 1: return 0
stack = []
for char in S:
if char=="(":
stack.append(char)
else:
if len(stack) > 0:
stack.pop()
else:
return 0
if len(stack) > 0: return 0
return 1