leetcode 20 -- Valid Parentheses

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.

题意:
实现括号匹配

思路:
括号匹配问题我们一般使用栈来辅助,每次先判断栈是否为空,1.不为空我们则用栈顶元素和新元素进行匹配,如果匹配上则pop出栈,否则push入栈,2.如果栈为空我们就push入栈

代码:

class Solution {
public:
    bool isValid(string s) {
        stack<char> sk;
        for(char c : s){
            if(!sk.empty()){
                char tmp = sk.top();
                if((tmp == '(' && c == ')') ||
                   (tmp == '[' && c == ']') ||
                   (tmp == '{' && c == '}')){
                       sk.pop();
                   }else{
                       sk.push(c);
                   }
            }else{
                sk.push(c);
            }
        }
        if(sk.empty()){
            return true;
        }else{
            return false;
        }
    }
};

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