zoukankan      html  css  js  c++  java
  • [LeetCode] 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.

    这题虽然简单但是我也没有一次就AC,问题在于取top和pop的时候忘了做异常判断,切记切记。

    此外找conterpart也许是个比较头疼的问题,但是用hashmap就方便多了

    map<char, char> conterpart;
    
    bool isValid(string s) {
        conterpart['('] = ')';
        conterpart['['] = ']';
        conterpart['{'] = '}';
        
        if (s.empty()) return true;
        stack<char> st;
        for (int i = 0; i < s.size(); i++) {
            char c = s.at(i);
            if (c == '(' || c == '[' || c == '{') {
                st.push(c);
            }
            else if (c == ')' || c == ']' || c == '}'){
                if (st.empty()) return false;
                if ( conterpart[st.top()] != c) {
                    return false;
                }
                else {
                    st.pop();
                }
            }
        }
        
        if (st.empty()) {
            return true;
        }
        return false;
    }
  • 相关阅读:
    .NET 第一天
    C# 多线程操作同一文件
    c# 进制转换-续
    C# 进制转化
    DevExpress.Utils.ToolTipLocation
    gridView 练习
    dashboard 数据绑定的时候 addTable 是视图
    gridLookUpEdit1
    gridview1 设置 内容居中 标题剧中
    LOOKupE
  • 原文地址:https://www.cnblogs.com/agentgamer/p/4099123.html
Copyright © 2011-2022 走看看