LeetCode题目:Valid Parentheses

By | 2012 年 11 月 6 日

用一个stack解决问题,从头到尾扫描一下,遇到左括号压栈,遇到右括号就将stack的top元素和其配对弹出。如果中间遇到问题不能配对,或者到最后stack不空,就返回false



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.



代码:8ms过大集合

class Solution {
public:
    bool isValid(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        stack lefts;
        for(int i = 0 ; i < s.size() ;++i) {
            char c = s[i];
            if(c == '(' || c == '[' || c == '{') {
                lefts.push(c);
            } else {
                if (lefts.size() == 0) return false;
                char top = lefts.top();
                if (c == ')') {
                    if(top != '(') return false;
                } else if ( c == ']' ) {
                    if(top != '[') return false;
                } else if ( c == '}' ){
                    if(top != '{') return false;
                }
                lefts.pop();
            }
        }
        return lefts.size() == 0;
    }
};

发表评论

电子邮件地址不会被公开。 必填项已用*标注