-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalid-parentheses.js
More file actions
51 lines (47 loc) · 1.67 KB
/
valid-parentheses.js
File metadata and controls
51 lines (47 loc) · 1.67 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
40
41
42
43
44
45
46
47
48
49
50
51
//Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
//The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
console.log(isValid("[({(())}[()])]"), 'true');
console.log(isValid('(([]){})'), 'true');
console.log(isValid('(([]){})'), 'true');
console.log(isValid('(())'), 'true');
console.log(isValid('()[]{}'), 'true');
console.log(isValid('{[(())]}'), 'true');
console.log(isValid('[{}]'), 'true');
console.log(isValid('()'), 'true');
console.log(isValid('[((){)])'), 'flase');
console.log(isValid('{{[()]}})'), 'flase');
console.log(isValid('{{)}'), 'flase');
console.log(isValid('{)'), 'flase');
function isValid(string) {
var testArray = string.split('');
let stringLength = testArray.length;
if (stringLength % 2 === 1) {
return false;
}
for (i = 0; i < stringLength; i++) {
testArray.forEach(function(inputArg, index, inputArray) {
switch (inputArg) {
case '[':
if (inputArray[index + 1] === ']') {
testArray.splice(index, 2);
}
break;
case '{':
if (inputArray[index + 1] === '}') {
testArray.splice(index, 2);
}
break;
case '(':
if (inputArray[index + 1] === ')') {
testArray.splice(index, 2);
}
break;
}
});
}
if (testArray.length === 0) {
return true;
} else {
return false;
}
};