题目:

给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

    左括号必须用相同类型的右括号闭合。
    左括号必须以正确的顺序闭合。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法:

思路:一开始,我使用栈作为s的存储,遇到括号在经过选择后就存入栈,这个选择包括,栈的顶部是(时,要存的是),那就pop一下,这样(和)就一起消失了,继续下一个循环。然后中括号和大括号同样处理。但是遇到了内存溢出的问题!简直horrible!!!!

代码贴一下,不知道有没有大神可以告诉我哪里错了,,,,好难过。。。

class Solution {

public:
    bool isValid(string s) {
        //内存溢出防止!----但是问题出在哪里我不知道。。horrible
        stack<char> sta;
        int i = 0;
        int l = s.size();
        sta.push(s[i]);
        while(l--){
            i++;
            if(sta.top() == '(' && s[i] == ')'){
                sta.pop();
            }else if(sta.top() == '{' && s[i] == '}'){
                sta.pop();
            }else if(sta.top() == '[' && s[i] == ']'){
                sta.pop();
            }else{
                sta.push(s[i]);
            }
        }
        return sta.empty();      
    }
};

然后看了大佬的思路:动画

代码如下:

class Solution {

public:
    bool isValid(string s) {
        //内存溢出防止!
        stack<char> sta;
        int l = s.size();

        for(int i = 0; i<l;i++){
            if(s[i] == '(') 
                sta.push(')');
            else if(s[i] == '{') 
                sta.push('}');
            else if(s[i] == '[')
                sta.push(']'); 
            else if(sta.empty() || sta.top() != s[i])
                return false;
            else if(sta.top() == s[i])
                sta.pop();
        }
        return sta.empty();      
    }
};


后序!!!!!

我的那个代码知道哪里的问题了!!我在sta的top判断之前没有判空,加上判空就可以了!

class Solution {

public:
    bool isValid(string s) {
        //内存溢出防止!
        stack<char> sta;
        int i = 0;
        int l = s.size();
        sta.push(s[i]);
        for(i = 1;i < l; i++){
            if(sta.empty()){
                sta.push(s[i]);
            }else{
                if(sta.top() == '(' && s[i] == ')'){
                    sta.pop();
                }else if(sta.top() == '{' && s[i] == '}'){
                    sta.pop();
                }else if(sta.top() == '[' && s[i] == ']'){
                    sta.pop();
                }else{
                    sta.push(s[i]);
                }
            }
            
        }
        return sta.empty();      
    }
};