ITPub博客

首页 > 应用开发 > IT综合 > 算法Valid Parentheses

算法Valid Parentheses

原创 IT综合 作者:dongyu2013 时间:2014-05-04 09:07:03 0 删除 编辑

点击(此处)折叠或打开

  1. public static boolean isValid(String s) {
  2.     HashMap<Character, Character> map = new HashMap<Character, Character>();
  3.     map.put(\'(\', \')\');
  4.     map.put(\'[\', \']\');
  5.     map.put(\'{\', \'}\');
  6.  
  7.     Stack<Character> stack = new Stack<Character>();
  8.  
  9.     for (int i = 0; i < s.length(); i++) {
  10.         char curr = s.charAt(i);
  11.  
  12.         if (map.keySet().contains(curr)) {
  13.             stack.push(curr);
  14.         } else if (map.values().contains(curr)) {
  15.             if (!stack.empty() && map.get(stack.peek()) == curr) {
  16.                 stack.pop();
  17.             } else {
  18.                 return false;
  19.             }
  20.         }
  21.     }
  22.  
  23.     return stack.empty();
  24. }

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29012686/viewspace-1153230/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2013-12-25

  • 博文量
    263
  • 访问量
    238070