Code Capriccio - Stack and Queue - Valid Parentheses

valid parentheses

This section corresponds to Code Random Notes: Code Random Notes , and the corresponding video link is: Stack’s Specialty! | LeetCode: 20. Valid brackets_bilibili_bilibili

exercise

Question link: 20. Valid brackets - LeetCode

Given a string s that only includes '(', ')', '{', '}', '[', ']', determine whether the string is valid.

A valid string must satisfy:

  • The opening bracket must be closed by a closing bracket of the same type.
  • Opening brackets must be closed in the correct order.
  • Every right bracket has a corresponding left bracket of the same type.
示例 2:
输入:s = "()[]{}"
输出:true
示例 3:
输入:s = "(]"
输出:false

My solution

First of all, if the string has an odd number of digits, it must not all match. The bracket matching problem, if you have studied data structures, you will know that this is a typical problem solved by using the stack.

Traverse the string. If the current element matches the element on the top of the stack, pop the element on the top of the stack. If the last stack is empty, it means that everything matches. If it is not empty, it means that everything does not match.

The problem lies in a pair of brackets, such as "("and")", which are unequal elements. There is no way to simply use equality to determine a pair of parentheses directly.

However, if you look at the ASCII of three pairs of brackets, you will find that: () are 40 and 41 respectively; {} are 123 and 125 respectively, and [] are 91 and 93 respectively. I believe you have seen the pattern. The value on the right is 1 or 2 larger than the one on the left. In this way, you can use the difference to determine whether it is a pair.

Note that the question clearly states that the string only contains the elements in the three pairs of brackets, so the difference can be used to judge

class Solution {
    
    
   public:
    bool isValid(string s) {
    
    
        if (s.size() % 2 != 0) {
    
    
            return false;
        }
        stack<int> myStack;
        for (int i = 0; i < s.size(); i++) {
    
    
            int tmp = myStack.empty() ? 0 : s[i] - myStack.top();
            // 差值为1或者为2说明为一对
            if (tmp == 1 || tmp == 2) {
    
    
                myStack.pop();  // 弹出来栈中已匹配的左符号
            } else {
    
    
                myStack.push(s[i]);  // 不匹配则push当前元素
            }
        }
        return myStack.empty();
    }
};
  • Time complexity: O( nnn ). where n is the length of string s
  • Space complexity: O( nnn ). A stack needs to be used to store the elements of the string, where n is the length of the string s

Code random recording solution

My solution is to use the difference value to determine whether it is a pair, while the code capricious record is to use multiple ifs to determine various situations. In comparison, my code is more concise, and I don’t need to write many ifs to judge multiple situations, but the code can be recorded more efficiently. The reason is that my solution must traverse all the elements before returning the result, and the code caprice may obtain the result during the traversal process.

Specifically, every time a left bracket is encountered, the corresponding right bracket is pushed onto the stack. In this way, when a right bracket is encountered, it can be judged whether the element on the top of the stack is equal to the current right bracket. If it is not equal or the stack is empty, false will be returned.

class Solution {
    
    
public:
    bool isValid(string s) {
    
    
        if (s.size() % 2 != 0) return false; // 如果s的长度为奇数,一定不符合要求
        stack<char> st;
        for (int i = 0; i < s.size(); i++) {
    
    
            if (s[i] == '(') st.push(')');
            else if (s[i] == '{') st.push('}');
            else if (s[i] == '[') st.push(']');
            // 第三种情况:遍历字符串匹配的过程中,栈已经为空了,没有匹配的字符了,说明右括号没有找到对应的左括号 return false
            // 第二种情况:遍历字符串匹配的过程中,发现栈里没有我们要匹配的字符。所以return false
            else if (st.empty() || st.top() != s[i]) return false;
            else st.pop(); // st.top() 与 s[i]相等,栈弹出元素
        }
        // 第一种情况:此时我们已经遍历完了字符串,但是栈不为空,说明有相应的左括号没有右括号来匹配,所以return false,否则就return true
        return st.empty();
    }
};

  • Time complexity: O( nnn ). where n is the length of string s
  • Space complexity: O( nnn ). A stack needs to be used to store the elements of the string, where n is the length of the string s

おすすめ

転載: blog.csdn.net/zss192/article/details/130116482