LeetCode OJ--Valid Parentheses

http://oj.leetcode.com/problems/valid-parentheses/

对栈的考察,看括号的使用方式是否合法。

class Solution {
public:
    bool isValid(string s) {
        if(s.empty() || s == "")
            return true;
        if(s.size()%2!= 0)
            return false;
        int i = 0;
        stack<char> myStack;
        while(i!=s.size())
        {
            if(s[i] == '(' || s[i] == '{' || s[i] == '[')
                myStack.push(s[i]);
            else
            {
                if(myStack.empty())
                    return false;
                char chStackTop = myStack.top();
                myStack.pop();
                if(s[i]== ')' && chStackTop!= '(' || s[i]== '}' && chStackTop!= '{' ||s[i]== ']' && chStackTop!= '[' )
                    return false;
                else if(s[i]!= ')' &&  s[i]!= '}' && s[i]!= ']')
                    return false;
            }
            i++;
        }
        if(myStack.empty())
            return true;
        else
            return false;
    }
};
原文地址:https://www.cnblogs.com/qingcheng/p/3550012.html