forked from ssitu001/toyProblemPractice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbalancedBrackets.js
53 lines (48 loc) · 1.25 KB
/
balancedBrackets.js
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
52
53
balancedBrackets.js
/*
* write a function that takes a string of text and returns true if
* the parentheses are balanced and false otherwise.
*
* Example:
* balancedParens('('); // false
* balancedParens('()'); // true
* balancedParens(')('); // false
* balancedParens('(())'); // true
*
* Step 2:
* make your solution work for all types of brackets
*
* Example:
* balancedParens('[](){}'); // true
* balancedParens('[({})]'); // true
* balancedParens('[(]{)}'); // false
*
* Step 3:
* ignore non-bracket characters
* balancedParens(' var wow = { yo: thisIsAwesome() }'); // true
* balancedParens(' var hubble = function() { telescopes.awesome();'); // false
*
*
*/
function balancedParens(input){
let brackets = {"[": "]", "{": "}", "(": ")"};
let cache = [];
let current;
let popped;
for (let i = 0; i < input.length; i++) {
if (input[i] === "(" || input[i] === '[' || input[i] === '{') {
current = input[i];
cache.push(input[i]);
} else {
popped = cache.pop();
//check for the matching closing bracket
if (current !== brackets[popped]) {
return false;
}
}
}
if (cache.length) {
return false;
}
return true;
}