-
Notifications
You must be signed in to change notification settings - Fork 44
/
Problem27.js
43 lines (38 loc) · 1.15 KB
/
Problem27.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
// Problem 27
//
// This problem was asked by Facebook.
//
// Given a string of round, curly, and square open and closing brackets, return whether the brackets are balanced (well-formed).
//
// For example, given the string "([])[]({})", you should return true.
//
// Given the string "([)]" or "((()", you should return false.
//
// https://leetcode.com/problems/valid-parentheses/description/
//
// O(N) Time and Space Complexity
// N is the length of the string
function validBrackets(string) {
const stack = [];
for (let i = 0; i < string.length; i++) {
const bracket = string.charAt(i);
// push opening brackets onto stack
if (bracket === '(' || bracket === '[' || bracket === '{')
stack.push(bracket);
else {
// closing brackets
const openingBracket = stack.pop();
if (openingBracket === undefined) return false;
if (!isMatch(openingBracket, bracket)) return false;
}
}
return stack.length === 0;
}
function isMatch(opening, closing) {
return (
(opening === '(' && closing === ')') ||
(opening === '[' && closing === ']') ||
(opening === '{' && closing === '}')
);
}
export default validBrackets;