1. 程式人生 > >有效的括號序列

有效的括號序列

class Solution {
public:
    /**
     * @param s A string
     * @return whether the string is a valid parentheses
     */
    bool isValidParentheses(string& s) {
         if(s.length()==0||s.length()%2!=0)
         { return false; }
         stack<char> S;
         for(int i=0;i<s.length();i++)
         { if(s[i]=='('||s[i]=='['||s[i]=='{')
            { S.push(s[i]); }
           else if(s[i]==')')
                {if(!S.empty()&&S.top()=='(')
                   {S.pop();}
                 else
                 {return false;
                  break;}
                }
           else if(s[i]==']')
                {if(!S.empty()&&S.top()=='[')
                   {S.pop();}
                 else
                 {return false;
                  break;}
                }
           else if(s[i]=='}')
                {if(!S.empty()&&S.top()=='{')
                   {S.pop();}
                 else
                 {return false;
                  break;}
                } 
            }
        if(!S.empty())
        {return false;}// Write your code here
    }
};