# 面试官：你工作了3年了，这道算法题你都答不出来？

9月又是换工作的最佳时机。我幻想着只要换一份工作，就可以离开这个“破碎的地方”，赚更多的钱，做最舒服的事情，但事与愿违。 #### 有效括号

``````Input: s = "()"
Output: true``````

``````Input: s = "()[]{}"
Output: true``````

``````Input: s = "(]"
Output: false``````

``````Input: s = "([)]"
Output: false``````

``````Input: s = "{[]}"
Output: true``````

• 1 <= s.length <= 104
• s 仅由括号‘()[]{}’组成

• 字符串 s 的长度必须是偶数，不能是奇数（成对匹配）。
• 右括号前面必须有左括号。

#### 方法一：暴力消除法

``````Input: s = "{[()]}"

Step 1: The pair of () can be eliminated, and the result s is left with {[]}
Step 2: The pair of [] can be eliminated, and the result s is left with {}
Step 3: The pair of {} can be eliminated, and the result s is left with '', so it returns true in line with the meaning of the question``````

``````const isValid = (s) => {
while (true) {
let len = s.length
// Replace the string with '' one by one according to the matching pair
s = s.replace('{}', '').replace('[]', '').replace('()', '')
// There are two cases where s.length will be equal to len
// 1. s is matched and becomes an empty string
// 2. s cannot continue to match, so its length is the same as the len at the beginning, for example ({], len is 3 at the beginning, and it is still 3 after matching, indicating that there is no need to continue matching, and the result is false
if (s.length === len) {
return len === 0
}
}
}``````

#### 方法二：使用“栈”来解决

``````Input: abc
Output: cba``````

“abc”和“cba”是对称的，所以我们可以尝试从堆栈的角度来解析：

``````Input: s = "{[()]}"

Step 1: read ch = {, which belongs to the left bracket, and put it into the stack. At this time, there is { in the stack.

Step 2: Read ch = [, which belongs to the left parenthesis, and push it into the stack. At this time, there are {[ in the stack.

Step 3: read ch = (, which belongs to the left parenthesis, and push it into the stack. At this time, there are {[( in the stack.

Step 4: Read ch = ), which belongs to the right parenthesis, try to read the top element of the stack (and ) just match, and pop ( out of the stack, at this time there are {[.

Step 5: Read ch = ], which belongs to the right parenthesis, try to read the top element of the stack [and ] just match, pop the [ out of the stack, at this time there are {.

Step 6: Read ch = }, which belongs to the right parenthesis, try to read the top element of the stack { and } exactly match, pop { out of the stack, at this time there is still '' in the stack.

Step 7: There is only '' left in the stack, s = "{[()]}" conforms to the valid bracket definition and returns true.``````

``````const isValid = (s) => {
// The empty string character is valid
if (!s) {
return true
}
const leftToRight = {
'(': ')',
'[': ']',
'{': '}'
}
const stack = []
for (let i = 0, len = s.length; i < len; i++) {
const ch = s[i]
// Left parenthesis
if (leftToRight[ch]) {
stack.push(ch)
} else {
// start matching closing parenthesis
// 1. If there is no left parenthesis in the stack, directly false
// 2. There is data but the top element of the stack is not the current closing parenthesis
if (!stack.length || leftToRight[ stack.pop() ] !== ch) {
return false
}
}
}
// Finally check if the stack is empty
return !stack.length
}``````

#### 最后      51CTO技术栈公众号 