-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
const bracketMap = { | ||
"]": -1, | ||
")": -2, | ||
"}": -3, | ||
"[": 1, | ||
"(": 2, | ||
"{": 3, | ||
}; | ||
|
||
var isValid = function (s) { | ||
if (bracketMap[s[0]] < 0) { | ||
return false; | ||
} | ||
|
||
const stack = []; | ||
|
||
for (let i = 0; i < s.length; i += 1) { | ||
const symbol = bracketMap[s[i]]; | ||
|
||
if (isOpenBracket(symbol)) { | ||
stack.push(symbol); | ||
continue; | ||
} | ||
|
||
if (isEmptyStack(stack)) { | ||
return false; | ||
} | ||
|
||
if (stack[stack.length - 1] === symbol * -1) { | ||
stack.pop(); | ||
} else { | ||
stack.push(symbol); | ||
} | ||
} | ||
|
||
return isEmptyStack(stack); | ||
}; | ||
|
||
function isEmptyStack(stack) { | ||
return stack.length === 0; | ||
} | ||
|
||
function isOpenBracket(symbol) { | ||
return symbol > 0; | ||
} |