Last active
March 25, 2021 08:04
-
-
Save JQChan/7b7a106317f2e011496c07e0ec482c19 to your computer and use it in GitHub Desktop.
栈的应用:实现平衡括号算法
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
import { Stack } from './Stack'; | |
/** 平衡括号算法 */ | |
function parenthesesChecker(symbols: string) { | |
const stack = new Stack<string>(); | |
const opens = '([{'; | |
const closers = ')]}'; | |
let balanced = true; | |
let index = 0; | |
let symbol; | |
let top; | |
while (index < symbols.length && balanced) { | |
symbol = symbols[index]; | |
if (opens.indexOf(symbol) >= 0) { | |
stack.push(symbol); | |
} else if (stack.isEmpty()) { | |
balanced = false; | |
} else { | |
top = stack.pop(); | |
if (!(opens.indexOf(top) === closers.indexOf(symbol))) { | |
balanced = false; | |
} | |
} | |
index++; | |
} | |
return balanced && stack.isEmpty(); | |
} | |
// console.log('([])', parenthesesChecker('([])')); // ([]) true | |
// console.log('{([])}', parenthesesChecker('{([])}')); // {([])} true | |
// console.log('(([()])))', parenthesesChecker('(([()])))')); // (([()]))) false | |
// console.log('[()[]()]()()', parenthesesChecker('([()[]()])()')); // ([()[]()])() true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment