首页 > 其他 > 详细

Valid Parentheses

时间:2019-02-24 16:01:51      阅读:177      评论:0      收藏:0      [点我收藏+]

题目:

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.

 

解答:

 1 public class Solution {
 2 
 3     private static final Map<Character, Character> map = new HashMap<Character, Character>() {{
 4         put(‘(‘, ‘)‘);
 5         put(‘{‘, ‘}‘);
 6         put(‘[‘, ‘]‘);
 7     }};
 8 
 9     public boolean isValid(String s) {
10         Stack<Character> stack = new Stack<>();
11         for(Char c : s.toCharArray()) {
12             if(map.contaisKey(c)) {
13                 stack.push(c);
14             } else if(stack.isEmpty() || map.get(stack.pop()) != c) {
15                 return false;
16             }
17         }
18 
19         return stack.isEmpty();
20     }
21 
22     public static void main(String[] args) {
23         String s = "[{}]";
24         System.out.println(isValid(s));
25     }
26 }

技术分享图片

 

Valid Parentheses

原文:https://www.cnblogs.com/wylwyl/p/10426418.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!