leetcode678+括号匹配,stack使用掌握规

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013554860/article/details/83477092

https://leetcode.com/problems/valid-parenthesis-string/description/

class Solution {
public:
    bool checkValidString(string s) {
        stack<int> left, star;
        for(int i=0; i<s.size(); i++){
            if(s[i]=='*') star.push(i);
            else if(s[i]=='(') left.push(i);
            else{ // )
                if(left.empty()&&star.empty()) return false;
                if(!left.empty()) left.pop();
                else star.pop();
            }
        }
        while(!left.empty()&&!star.empty()){
            if(left.top() > star.top()) return false; // *( 是不行的
            left.pop(); star.pop();
        }
        return left.empty();  // star 可以为empty string
    }
};

猜你喜欢

转载自blog.csdn.net/u013554860/article/details/83477092