zoukankan      html  css  js  c++  java
  • leetcode 20 有效的括号

    简介

    栈的应用

    code

    class Solution {
        stack<char> ss;
        map<char, char> m;
    public:
        bool isValid(string s) {
            m['('] = ')';
            m['{'] = '}';
            m['['] = ']';
            for(auto it : s){
               if(it == '(' || it == '{' || it == '[') {
                  ss.push(it);
               }
               else {
                   if(ss.empty()) {
                       return false;
                   }
                   if(m[ss.top()] != it){
                       return false;
                   }else{
                       ss.pop();
                   }
               }
            }
            if(ss.size() == 0){
                return true;
            }
            return false;
        }
    };
    
    class Solution {
        public boolean isValid(String s) {
            int n = s.length();
            if (n % 2 == 1) {
                return false;
            }
    
            Map<Character, Character> pairs = new HashMap<Character, Character>();  // 类似char 的原始类型??
                pairs.put(')', '(');
                pairs.put(']', '[');
                pairs.put('}', '{');
            
            Deque<Character> stack = new LinkedList<Character>(); // 用deque来模拟栈操作
            for (int i = 0; i < n; i++) {
                char ch = s.charAt(i); // 从string中取数据
                if (pairs.containsKey(ch)) { // map 使用containsKey 判断是否存在. 不像C++ 可以重载括号的缘故.
                    if (stack.isEmpty() || stack.peek() != pairs.get(ch)) {
                        return false;
                    }
                    stack.pop();
                } else {
                    stack.push(ch);
                }
            }
            return stack.isEmpty(); // 专门和c++不同的isEmpty()操作.
        }
    }
    
    作者:LeetCode-Solution
    链接:https://leetcode-cn.com/problems/valid-parentheses/solution/you-xiao-de-gua-hao-by-leetcode-solution/
    来源:力扣(LeetCode)
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
    
    Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
  • 相关阅读:
    Oracle配置手册
    Vim配置手册
    高斯消元
    dp专场的蒟蒻题解
    mac 软件意外退出
    spring security整体流程
    服务启动shell脚本
    nohup 启动命令
    linux service脚本
    docker 安装prometheus和grafna
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/14783124.html
Copyright © 2011-2022 走看看