問題描述
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;
}
}
}
if (stack.length > 0) return false;
return true;
}