Valid Parentheses

题目:

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

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

分析:

这是一道应用stack的典型题目,因为会有([)]这样的情况,用integer计数的方法有bug,无法区分上述情况。

除此之外,这道题目考察了switch语句的syntax。

解法:

class Solution {
public:
    /**
     * @param s A string
     * @return whether the string is a valid parentheses
     */
    bool isValidParentheses(string& s) {
        // Write your code here
        stack<char> myStack;
        for (int i = 0; i < s.size(); i++) {
            switch (s[i]) {
                case '(' :  {
                    myStack.push(s[i]);
                    break;
                }
                case '[' :  {
                    myStack.push(s[i]);
                    break;
                }
                case '{' :  {
                    myStack.push(s[i]);
                    break;
                }

                case '}' :  {
                    if (myStack.empty() || myStack.top() != '{') {
                        return false;
                    } else {
                        myStack.pop();
                    }
                    break;
                }

                case ']' :  {
                    if (myStack.empty() || myStack.top() != '[') {
                        return false;
                    } else {
                        myStack.pop();
                    }
                    break;
                }

                case ')' :  {
                    if (myStack.empty() || myStack.top() != '(') {
                        return false;
                    } else {
                        myStack.pop();
                    }
                    break;
                }

                default : return false;
            }
        }
        if (!myStack.empty() ) {
            return false;
        }

        return true;
    }
};

results matching ""

    No results matching ""