Valid Parentheses

题目:

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 }

 

posted @ 2019-02-24 15:39  林木声  阅读(314)  评论(0编辑  收藏  举报