Correct Parenthesis (Stack)

Problem

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.

input

  • A string of parentheses is entered on the first line
  • The maximum length of a string is 30
(()(()))(()

output

Outputs YES and NO on the first line.

NO

Solution

use stack

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;
}

simpler

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;
}