If parentheses are entered, it outputs “YES” if it is a valid parenthesis, and “NO” if it is not correct.
(())() This is the correct placement of the pair of parentheses, but (()())) is not the correct parentheses.
(()(()))(()
Outputs YES and NO on the first line.
NO
function solution(s) {
let answer = 'YES',
stack = [];
if (!s.length % 2) return 'NO';
for (let x of s) {
if (x === '(' && stack[stack.length - 1] === ')') stack.pop();
if (x === ')' && stack[stack.length - 1] === '(') stack.pop();
stack.push(x);
}
if (stack.length) return 'NO';
return answer;
}
function solution(s) {
let answer = 'YES',
stack = [];
for (let x of s) {
if (x === '(') stack.push(x);
else {
// if there is no first "(" from the stack, ")" is gonna be problem, so return earlier
if (!stack.length) return 'NO';
stack.pop();
}
}
if (!stack.length) return 'NO';
return answer;
}