问题描述
Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
翻译:给定一个仅包含(
、)
、[
、]
、{
、}
的字符串,判断输入字符串是否合法;
当且仅当输入字符串满足以下条件时才合法:
- 括号由同类型括号闭合;
- 括号的闭合以正确的顺序;
注意空字符串也是合法的;
实现原理
栈数据结构是后进先出的形式,可以满足我们的需求;每次遇到左括号([{
时进行入栈,然后遇到右括号)]}
时进行出栈并判断出栈元素是否与当前字符匹配,如果匹配成功则继续;直至遍历整个字符串;
遍历结束后,如果栈为空,则完全匹配,字符串合法;负责字符串不合法;
show you the code
// code source: https://yuchengkai.cn/docs/cs/dataStruct.html#%E5%AE%9E%E7%8E%B0
const isStrValid = s => {
const map = {
"(": -1,
")": 1,
"[": -2,
"]": 2,
"{": -3,
"}": 3
}
let stack = [];
for (let i = 0; i < s.length; i++) {
if (map[s[i]] < 0) {
stack.push(s[i]);
} else {
let top = stack.pop();
if (map[top] + map[s[i] !== 0) {
return false;
}
}
}
return stack.length === 0;
}