当前位置:网站首页>20. valid brackets

20. valid brackets

2022-06-11 08:56:00 Drag is me

leetcode Force button to brush questions and punch in

subject :20. Valid parenthesis
describe : Given one only includes ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ String s , Determines whether the string is valid .

Valid string needs to meet :

Opening parentheses must be closed with closing parentheses of the same type .
The left parenthesis must be closed in the correct order .

Their thinking

1、 Parentheses encountered , It is basically a stack solution ;
2、 The stack is empty. , direct push Come in ; Stack is not empty. , Compare whether the stack top element and the new element are paired , Pairing is directly out of the stack ;
3、 Finally, judge whether the stack is empty , All are paired. The stack must be empty , return true, Instead, return to false;

Source code ##

class Solution {
    
public:
    bool ispair(char a, char b) {
    
        switch (a) {
    
            case '(':
                if (b == ')') return true;
                else return false;
            case '{':
                if (b == '}') return true;
                else return false;
            case '[':
                if (b == ']') return true;
                else return false;
            default:
                return false;
        }
    }
    bool isValid(string s) {
    
        stack<char>sc;
        for (int i = 0; i < s.size(); ++i) {
    
            if (sc.empty()) {
    
                sc.push(s[i]);
                continue;
            } else {
    
                char temp = sc.top();
                if (ispair(temp, s[i])) sc.pop(); 
                else sc.push(s[i]);
            }
            
        }
        if (sc.empty()) return true;
        else return false;    
    }  
};
原网站

版权声明
本文为[Drag is me]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110855010777.html