LeetCode 20. 有效的括号

Posted 程序字母K

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 20. 有效的括号相关的知识,希望对你有一定的参考价值。

给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
1.左括号必须用相同类型的右括号闭合。
2.左括号必须以正确的顺序闭合。

class Solution {
public:
    bool isValid(string s) {
        if(s.size()%2==1)
        return false;
//方法一:
        //每种情况的分析
        // std::stack<char> st;
        // for(int i=0;i<s.size();++i){
        // if(s[i]=='('||s[i]=='['||s[i]=='{'){
        //     st.push(s[i]);
        // }else{
        //     if(st.empty()) return false;
        //     if(s[i]==')' && st.top()!='(') return false;
        //     if(s[i]==']' && st.top()!='[') return false;
        //     if(s[i]=='}' && st.top()!='{') return false;
        //     st.pop();
        // }
        // }
        // if(st.empty())
        // return true;
        // return false;

//方法二:替换法,,总有(){}[]找出来,删了,直到找不到,如果还有值就false;
        //string::replace(pos,2,"");
        //pos位置必须是string内的下标,所以必需判断是否查找到
        //string::find(string);//找到返回下标,没找到返回string::npos(-1)
        int length=s.size();
        for(int i=0;i<length/2;++i){
            if(s.find("()")!=-1)
            s.replace(s.find("()"),2,"");
            else if(-1!=s.find("[]"))
            s.replace(s.find("[]"),2,"");
            else if(-1!=s.find("{}"))
            s.replace(s.find("{}"),2,"");
        }
        return s.size()==0;
        
//方法三:运气法,,代码我给了,对不对看你
       // return random()%100 < 50;
    }
};

以上是关于LeetCode 20. 有效的括号的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 20. 有效的括号

leetcode20有效的括号

LeetCode第20题——有效的括号

LeetCode:有效的括号20

leetcode-20.有效的括号

LeetCode 20. 有效的括号