LeetCode : Valid Parentheses

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

The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.

class Solution {
public:
    bool isValid(string s) {
        stack<char>brack;
        int i = 0;
        while(i<s.size())
        {
            char c = s[i];
            if(c=='('||c=='['||c=='{')
                   brack.push(c);
            else
            {
                if(brack.size()==0)
                    return false;
                char pre = brack.top();
                switch(c)
                {
                    case ')':
                       if(pre=='(')
                          brack.pop();
                       else
                          return false;
                       break;
                    case ']':
                       if(pre=='[')
                          brack.pop();
                       else
                          return false;
                          break;
                    case '}':
                       if(pre=='{')
                          brack.pop();
                       else
                          return false;
                          break;
                }
            }
            ++i;
        }
        if(brack.size()==0)
            return true;
        else
            return false;
    }
};

posted on 2017-04-11 21:23  gechen  阅读(105)  评论(0编辑  收藏  举报

导航