[leetcode] 20.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) {
        if(s.empty())return true;
        stack<char> signs;
        for(auto c : s) {
            switch(c) {
                case '(':signs.push(c);break;
                case '[':signs.push(c);break;
                case '{':signs.push(c);break;
                case ')':{
                    if(signs.empty() || signs.top() != '(')return false;
                    signs.pop();
                    break;
                }
                case ']':{
                    if(signs.empty() || signs.top() != '[')return false;
                    signs.pop();
                    break;
                }
                case '}':{
                    if(signs.empty() || signs.top() != '{')return false;
                    signs.pop();
                    break;
                }
            }
        }
        return signs.empty();
    }
};
發佈了239 篇原創文章 · 獲贊 2 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章