• LeetCode刷题记录_有效的括号


    题目:

    给定一个只包括 '('')''{''}''['']' 的字符串,判断字符串是否有效。

    有效字符串需满足:

    1. 左括号必须用相同类型的右括号闭合。
    2. 左括号必须以正确的顺序闭合。

    注意空字符串可被认为是有效字符串。

    示例 1:

    输入: "()"
    输出: true
    

    示例 2:

    输入: "()[]{}"
    输出: true
    

    示例 3:

    输入: "(]"
    输出: false
    

    示例 4:

    输入: "([)]"
    输出: false
    

    示例 5:

    输入: "{[]}"
    输出: true

    用栈的思想来解决最简单了,可惜stack完全没用过,用LinkedList模仿堆栈:

    class Solution {
        public boolean isValid(String s) {
            LinkedList<Character> list= new LinkedList<>();
            Map<Character,Character> map = new HashMap<>();
            map.put('}','{');
            map.put(')','(');
            map.put(']','[');
            int len= s.length();
            
            for(int i=0;i<len;i++){
                Character ch = new Character(s.charAt(i));
                if(!map.containsKey(ch)||list.size()==0)
                    list.addLast(ch);
                else{
                    if(list.get(list.size()-1).equals(map.get(ch)))
                        list.removeLast();
                    else
                        return false;
                }            
            }
           return list.isEmpty()?ture:false;
            
        }
    }
    

     感觉代码写的还是太丑了

  • 相关阅读:
    Yii2的View中JS代码添加
    Yii2命名规则
    Yii2 Redis的使用
    win7下php5.6安装redis扩展
    Ubuntu安装cuda
    Ubuntu 安装显卡驱动
    TensorFlow 图片resize方法
    anaconda的kernel对jupyter可见
    cuda和显卡驱动版本
    jupyter修改根目录
  • 原文地址:https://www.cnblogs.com/annofyf/p/9382547.html
Copyright © 2020-2023  润新知