博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
有效括号方法二
阅读量:6920 次
发布时间:2019-06-27

本文共 1154 字,大约阅读时间需要 3 分钟。

class Solution {

  // Hash table that takes care of the mappings.
  private HashMap<Character, Character> mappings;
  // Initialize hash map with mappings. This simply makes the code easier to read.
  public Solution() {
    this.mappings = new HashMap<Character, Character>();
    this.mappings.put(')', '(');
    this.mappings.put('}', '{');
    this.mappings.put(']', '[');
  }
  public boolean isValid(String s) {
    // Initialize a stack to be used in the algorithm.
    Stack<Character> stack = new Stack<Character>();
    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);
      // If the current character is a closing bracket.
      if (this.mappings.containsKey(c)) {
        // Get the top element of the stack. If the stack is empty, set a dummy value of '#'
        char topElement = stack.empty() ? '#' : stack.pop();
        // If the mapping for this bracket doesn't match the stack's top element, return false.
        if (topElement != this.mappings.get(c)) {
          return false;
        }
      } else {
        // If it was an opening bracket, push to the stack.
        stack.push(c);
      }
    }
    // If the stack still contains elements, then it is an invalid expression.
    return stack.isEmpty();
  }
}

转载于:https://www.cnblogs.com/wzhtql/p/10225691.html

你可能感兴趣的文章
VS 中 ExtJS 智能提示
查看>>
陈松松:视频营销效果不好,从这四个角度找原因
查看>>
Python代码调试技巧
查看>>
Nginx优化指南
查看>>
elasticsearch集群搭建手册
查看>>
如何正确认识XMind软件格式
查看>>
OSChina 周一乱弹 ——有2个小混蛋大晚上……
查看>>
JNI/NDK开发指南(二)——JVM查找java native方法的规则
查看>>
Installing / Updating Python on OS X
查看>>
Android解析XML文件
查看>>
Spring AOP前置通知和后置通知
查看>>
Windows 之间用rsync同步数据(cwRsyncServer配置)
查看>>
android gps定位
查看>>
JFinal AOP学习笔记
查看>>
idea 查看Java类字节码 自定义工具的使用
查看>>
“效果系列一”:jQuery 手风琴效果
查看>>
java相对路径获取(读取)文件
查看>>
VS上写helloworld
查看>>
反射机制——获取Class对象的三种方式
查看>>
react-native 初始化指定版本
查看>>