9
头图

foreword

Gold three silver four, it's the best time to change jobs again. I imagine that as long as I change jobs, I can leave this "bird place", take more money, and do the coolest things...

However, the reality is always cruel. Recently, a school girl is changing jobs. Before the interview, what handwritten Priomise, vue two-way binding principle, webpack optimization method, prepared a lot, I thought it was in my mind, but the result was in the algorithm I suffered a big loss, I didn't get the offer I wanted, and I doubted my life for a while. What kind of algorithm question can make the interviewer say to the girl, you have been working for 3 years, and you can't even know this algorithm question? Such cruel words?

valid parentheses problem

This is an original question on leetcode , which is intended to examine the candidate's mastery of the stack data structure. Let's look at the topic

Given a string s containing only '(', ')', '{', '}', '[', ']', determine whether the string is valid.
A valid string must satisfy:

  1. Opening parentheses must be closed with closing parentheses of the same type.
  2. Left parentheses must be closed in the correct order.

Example


示例 1:
输入:s = "()"
输出:true

示例 2:
输入:s = "()[]{}"
输出:true

示例 3:
输入:s = "(]"
输出:false

示例 4:
输入:s = "([)]"
输出:false

示例 5:
输入:s = "{[]}"
输出:true

Problem solving information

If we really haven't brushed the algorithm and don't know so many routines, it is very important to get as much information as possible through questions and examples.

Infer from the title:

  1. The length of the string s must be even, not odd ( match pairs).
  2. closing bracket must be followed bracket to meet the matching conditions and have symmetry.
  3. If the right parenthesis is not a left parenthesis, it must not be a valid parenthesis.

Violence Elimination Act

After getting the above information, Fattouyu thought that since [] , {} , and () appear in pairs, can I eliminate them one by one? If the final result is an empty string, doesn't that mean it meets the meaning of the question?

for example

输入:s = "{[()]}"

第一步:可以消除()这一对,结果s还剩{[]}

第二步: 可以消除[]这一对,结果s还剩{}

第三步: 可以消除{}这一对,结果s还剩'' 所以符合题意返回true

code implements

const isValid = (s) => {
  while (true) {
    let len = s.length
    // 将字符串按照匹配对,挨个替换为''
    s = s.replace('{}', '').replace('[]', '').replace('()', '')
    // 有两种情况s.length会等于len
    // 1. s匹配完了,变成了空字符串
    // 2. s无法继续匹配,导致其长度和一开始的len一样,比如({],一开始len是3,匹配完还是3,说明不用继续匹配了,结果就是false
    if (s.length === len) {
      return len === 0
    }
  }
}

The violent elimination method can still pass the use case of leetcode, but the performance is a bit worse, haha

image.png

stack problem solving

The second item in the problem-solving information emphasizes symmetry, and the stack (last-in, first-out) stacking and popping are just reversed, forming a clear symmetry.

Push: abc, pop: cba

abc
cba

So you can try to parse it from the perspective of the stack:

输入:s = "{[()]}"

第一步:读取ch = {,属于左括号,入栈,此时栈内有{
第二步:读取ch = [,属于左括号,入栈,此时栈内有{[
第三步:读取ch = (,属于左括号,入栈,此时栈内有{[(
第四步:读取ch = ),属于右括号,尝试读取栈顶元素(和)正好匹配,将(出栈,此时栈内还剩{[
第五步:读取ch = ],属于右括号,尝试读取栈顶元素[和]正好匹配,将[出栈,此时栈内还剩{
第六步:读取ch = },属于右括号,尝试读取栈顶元素{和}正好匹配,将{出栈,此时栈内还剩''
第七步:栈内只能'',s = "{[()]}"符合有效的括号定义,返回true

code implements

const isValid = (s) => {
  // 空字符串符合条件
  if (!s) {
    return true
  }

  const leftToRight = {
    '(': ')',
    '[': ']',
    '{': '}'
  }
  const stack = []

  for (let i = 0, len = s.length; i < len; i++) {
    const ch = s[i]
    // 左括号
    if (leftToRight[ch]) {
      stack.push(ch)
    } else {
      // 右括号开始匹配
      // 1. 如果栈内没有左括号,直接false
      // 2. 有数据但是栈顶元素不是当前的右括号
      if (!stack.length || leftToRight[ stack.pop() ] !== ch) {
        return false
      }
    }
  }

  // 最后检查栈内还有没有元素,有说明还有未匹配则不符合
  return !stack.length
}

Although the violent solution is in line with our daily thinking, it is still a lot better than the stack structure solution.

image.png

end

In the interview, whether the algorithm should become an important indicator for evaluating candidates, we will not complain, but in recent years, almost every major factory has put the algorithm into the front-end interview. In order to get the favorite offer, review the data structure, It is still necessary to brush the questions. May you and I be treated gently by the algorithm.

前端胖头鱼
3.7k 声望6.2k 粉丝