天天看點

Leetcode 20: Valid Parentheses

//括号比對是典型的出棧入棧問題
           
class Solution {
public:
    bool isValid(string s) {
        vector<char> stack;
        if(s.length() <= 1 )
            return false;
        while(s.length() > 0)
        {
            if(s[0] == '(' || s[0] == '[' || s[0] == '{')
                stack.push_back(s[0]);   
           else if (stack.size() == 0)
			    return false;
            else
            {
                if(s[0] == ')' && stack[stack.size() - 1] == '('
                  || s[0] == ']' && stack[stack.size() - 1] == '['
                  || s[0] == '}' && stack[stack.size() - 1] == '{')
                    stack.pop_back();
                else
                    return false;
            }
            s = s.substr(1, s.length() - 1);
        }
     if (stack.size() != 0)
		return false;
	 else
		return true;
    }
};