The question
Given a string of opening and closing parentheses, check whether it’s balanced. We have 3 types of parentheses: round brackets: (), square brackets: [], and curly brackets: {}. Assume that the string doesn’t contain any other character than these. No spaces, words or numbers. Just to remind, balanced parentheses require every opening parenthesis to be closed in the reverse order opened. For example ‘([])’ is balanced but ‘([)]‘ is not.
My solution
I have faced similar problems in the past(building a calculator) so this exercise didn’t seem that hard:
– Start on the first character and repeat for each character
– If that character is an opening brace add it to a stack
– If that character is a closing brace pop from the stack
– If the popped brace matches the current brace then continue
– If the popped brace doesn’t match the current brace then fail
– At the end if the stack is not empty then fail
This seems to be the best solution for this problem, so lets see the code:
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
var stack = [];
function checkParentheses(word) {
var map = {
'(': ')',
'[': ']',
'{': '}'
};
for (var i = 0; i < word.length; i++) {
if (word[i] === '(' || word[i] === '[' || word[i] === '{') {
stack.push(word[i]);
} else {
var last = stack.pop();
if (word[i] !== map[last]) {
return false;
}
}
}
if (stack.length !== 0) {
return false;
}
return true;
}
function test() {
if (checkParentheses('([]{}){}[]') === true) {
console.log('success');
}
if (checkParentheses('([]{}{}[]') === false) {
console.log('success');
}
if (checkParentheses('([]{}){}[]}') === false) {
console.log('success');
}
}
test(); // Prints success three times
computer_science
algorithms
javascript
programming
]