20.Valid Parentheses(Stack-Easy)

转载请注明作者和出处:http://blog.csdn.net/c406495762

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.

题目: 判断字符串中的括号是否有效。要求括号成对出现,并且括号顺序对应上。例如:[12(fgsf)4]-有效、{d[]df34}-有效、{f3[aer)}-无效、{3)32}-无效。

思路: 使用for(char c : s)对字符串的每个元素操作,如果c为”(“、”[“、”{“,则进行入Stack操作。如果为”)”、”]”、”}”,则进行出Stack操作,并与stack.top()元素比对,如果成对,说明有效。

Language : cpp

class Solution {
public:
    bool isValid(string s) {
        stack<char> stk;
        for(char c : s){
            switch(c){
                case '(':
                case '[':
                case '{':stk.push(c);break;
                case ')':if(stk.empty() || stk.top() != '(') return false;else stk.pop();break;
                case ']':if(stk.empty() || stk.top() != '[') return false;else stk.pop();break;
                case '}':if(stk.empty() || stk.top() != '{') return false;else stk.pop();break;
                default:break;
            }
        }
        return stk.empty();
    }
};

你可能感兴趣的:(LeetCode,stack)