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> charStack;
        size_t i = 0;

        while(i != s.length())
        {
            char c = s[i];
            if (c != ')' && c != '}' && c != ']')
            {
                charStack.push(c);
            }
            else
            {
                if (charStack.size() == 0)
                   return false;

                char pre = charStack.top();
                switch(c)
                {
                case ')':
                    if (pre == '(')
                      charStack.pop();
                    else
                      return false;
                    break;

                case '}':
                    if (pre == '{')
                      charStack.pop();
                    else
                      return false;
                    break;

                case ']':
                    if (pre == '[')
                      charStack.pop();
                    else
                      return false;
                    break;
                }
            }
            ++i;
        }
        if (charStack.size() == 0)
           return true;
        else return false;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章