1 Star 0 Fork 0

ccyy-阿亮/datastructures_ts

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
balanced-symbols.ts 1.31 KB
一键复制 编辑 原始数据 按行查看 历史
mr-liuliang 提交于 2020-04-06 16:47 +08:00 . 利用栈解决平衡圆括号问题
import Stack from '../data-structures/stack-object';
/**
* 平衡圆括号(利用栈结构)
* 思路:将字符串里的左括号存进栈结构里,遍历到右括号时与栈顶元素相匹配(栈为空或者匹配不成功就判为false)
* @param symbols 目标字符串
*/
export function parenthesesChecker(symbols: string): boolean {
const begin = '([{';
const end = ')]}';
let index: number = 0;
const stack = new Stack<string>();
let balance: boolean = true;
while (index < symbols.length && balance) { // 遍历完或者找出不平衡
const symbol = symbols[index];
if (begin.indexOf(symbol) >= 0) {
stack.push(symbol); // 如果是左括号就存入栈
} else { // 当前符号是右括号
if (stack.isEmpty()) { // 当前符号是右括号,但栈里没有左括号了,无法平衡
balance = false;
} else { // 当前符号是右括号,栈里还有左括号
const top = stack.pop(); // 取出栈顶的左括号
if (!(begin.indexOf(top) === end.indexOf(symbol))) { // 该右括号与栈顶的左括号对应不上,无法平衡
balance = false;
}
}
}
index ++;
}
return balance && stack.isEmpty();
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
TypeScript
1
https://gitee.com/liawnliu/datastructures_ts.git
git@gitee.com:liawnliu/datastructures_ts.git
liawnliu
datastructures_ts
datastructures_ts
master

搜索帮助