【LeetCode】Valid Parentheses(C++)

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.


这道题主要是用到<stack>

代码:

class Solution {
public:
    bool isValid(string s) {
        stack<string> judge;
        
        if(s.substr(0,1)==")"||s.substr(0,1)=="]"||s.substr(0,1)=="}")
            return false;
        
        for(int i=0; i<s.size(); i++){
            
            if(s.substr(i,1)=="("||s.substr(i,1)=="["||s.substr(i,1)=="{")
              judge.push(s.substr(i,1));
            
            if(s.substr(i,1)==")"){
                if(judge.empty())
                    return false;
                if(judge.top()=="(")
                    judge.pop();
                else
                    judge.push(s.substr(i,1));
            }
            if(s.substr(i,1)=="]"){
                if(judge.empty())
                    return false;
                if(judge.top()=="[")
                    judge.pop();
                else
                    judge.push(s.substr(i,1));
            }
            if(s.substr(i,1)=="}"){
                if(judge.empty())
                    return false;
                if(judge.top()=="{")
                    judge.pop();
                else
                    judge.push(s.substr(i,1));
            }
        }
        if(judge.size()==0)
            return true;
        else
            return false;
           
    }
};

猜你喜欢

转载自blog.csdn.net/biongbiongdou/article/details/80207651