-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathvalid_parentheses.js
More file actions
30 lines (29 loc) · 1.07 KB
/
valid_parentheses.js
File metadata and controls
30 lines (29 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
var isValid = function (s) {
// Stack to store left symbols
const leftSymbols = [];
// Loop for each character of the string
for (let i = 0; i < s.length; i++) {
// If left symbol is encountered
if (s[i] === '(' || s[i] === '{' || s[i] === '[') {
leftSymbols.push(s[i]);
}
// If right symbol is encountered
else if (s[i] === ')' && leftSymbols.length !== 0 && leftSymbols[leftSymbols.length - 1] === '(') {
leftSymbols.pop();
} else if (s[i] === '}' && leftSymbols.length !== 0 && leftSymbols[leftSymbols.length - 1] === '{') {
leftSymbols.pop();
} else if (s[i] === ']' && leftSymbols.length !== 0 && leftSymbols[leftSymbols.length - 1] === '[') {
leftSymbols.pop();
}
// If none of the valid symbols is encountered
else {
return false;
}
}
return leftSymbols.length === 0;
};
console.log(isValid("()"));
console.log(isValid("()[]{}"));
console.log(isValid("(]"));
console.log(isValid("([)]"));
console.log(isValid("{[]}"));