【leetcode】20. Valid Parentheses 括号串的合法判断

1. 题目

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.

2. 思路

如果是有效的,则符合有序的先进后出序列,构造栈进行模拟验证。
顺序扫描,遇到左括号进栈,遇到右括号弹栈进行匹配,不匹配则失败。匹配则继续。
扫描完之后,如果占里还有数据,或者弹栈匹配时无数据可弹,都是失败。

3. 代码

class Solution {
public:
    Solution() {
        for (int i = 0; i < 128; i++) {
            wh[i] = 0;
            re[i] = false;
        }
        wh['('] = wh[')'] = 1;
        wh['['] = wh[']'] = 2;
        wh['{'] = wh['}'] = 3;
        re[')'] = re[']'] = re['}'] = true;
    }
    bool isValid(string s) {
        int len = s.length();
        if (len == 0) return true;
        
        vector<char> stack;
        for (int i = 0; i < len; i++) {
            char ch = s[i];
            if (re[ch]) {
                if (stack.empty()) return false;
                char last = stack.back();
                if (wh[last] != wh[ch]) {
                    return false;
                } else {
                    stack.pop_back();
                }
            } else {
                stack.push_back(ch);
            }
        }
        if (stack.empty()) return true;
        else return false;
    }
    
private:
    int wh[128];
    bool re[128];
};
    原文作者:knzeus
    原文地址: https://segmentfault.com/a/1190000007277149
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞