-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvalidParentheses.js
More file actions
39 lines (33 loc) · 1.03 KB
/
validParentheses.js
File metadata and controls
39 lines (33 loc) · 1.03 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
31
32
33
34
35
36
37
38
39
// Given a string s containing just the characters '(', ')', '{', '}', '[' and ']',
// determine if the input string is valid.
// An input string is valid if:
// Open brackets must be closed by the same type of brackets.
// Open brackets must be closed in the correct order.
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function (s) {
// Hash map for keeping track of mappings. This keeps the code very clean.
// Also makes adding more types of parenthesis easier
let closeMap = {
')': '(',
'}': '{',
']': '[',
};
// The stack to keep track of opening brackets.
let charStack = [];
// validate input
if (s === null || s === undefined) return false;
for (var i = 0; i < s.length; i++) {
let curChar = s.charAt(i);
let topElement;
if (closeMap[curChar] !== undefined) {
topElement = charStack.length === 0 ? '#' : charStack.pop();
if (topElement !== closeMap[curChar]) return false;
} else {
charStack.push(curChar);
}
}
return charStack.length === 0;
};