Skip to content

Instantly share code, notes, and snippets.

@JQChan
Last active March 25, 2021 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JQChan/7b7a106317f2e011496c07e0ec482c19 to your computer and use it in GitHub Desktop.
Save JQChan/7b7a106317f2e011496c07e0ec482c19 to your computer and use it in GitHub Desktop.
栈的应用:实现平衡括号算法
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