LeetCode.20有效地括号

用哈希表来简化括号匹配,总的思想还是当出现左括号时入栈,右括号时出栈并检查是否与当前有括号匹配。

 1 class Solution {
 2     public boolean isValid(String s) {
 3         int n = s.length();
 4         if (n % 2 == 1) {              //可以通过字符串长度的奇偶来过滤
 5             return false;
 6         }
 7 
 8         Map<Character, Character> pairs = new HashMap<Character, Character>() {{
 9             put(‘)‘, ‘(‘);
10             put(‘]‘, ‘[‘);
11             put(‘}‘, ‘{‘);
12         }};
13         Deque<Character> stack = new LinkedList<Character>();
14         for (int i = 0; i < n; i++) {
15             char ch = s.charAt(i);
16             if (pairs.containsKey(ch)) {
17                 if (stack.isEmpty() || stack.peek() != pairs.get(ch)) {
18                     return false;
19                 }
20                 stack.pop();
21             } else {
22                 stack.push(ch);
23             }
24         }
25         return stack.isEmpty();
26     }
27 }

我的代码:

 1 class Solution {
 2     public boolean isValid(String s) {
 3         Stack<Character> stack = new Stack<Character>();
 4         for(int i = 0;i < s.length(); i++){
 5             char c = s.charAt(i);
 6             if(c == ‘(‘ || c == ‘{‘ || c == ‘[‘){
 7                 stack.push(c);
 8             }
 9             else{
10                 if(stack.empty()) return false;
11                 if(c == ‘)‘ && stack.peek() == ‘(‘){
12                     stack.pop();
13                     continue;
14                 }else if(c == ‘]‘ && stack.peek() == ‘[‘){
15                     stack.pop();
16                     continue;
17                 }else if(c == ‘}‘ && stack.peek() == ‘{‘){
18                     stack.pop();
19                     continue;
20                 }
21                 else
22                     return false;
23             }
24         }
25         if(!stack.empty()) return false;
26         return true;
27     }
28 }

特殊方法:

 1 class Solution {
 2     public boolean isValid(String s) {
 3         while(s.contains("()")||s.contains("[]")||s.contains("{}")){
 4             if(s.contains("()")){
 5                 s=s.replace("()","");
 6             }
 7             if(s.contains("{}")){
 8                 s=s.replace("{}","");
 9             }
10             if(s.contains("[]")){
11                 s=s.replace("[]","");
12             }
13         }
14         return s.length()==0;
15     }
16 }

 

LeetCode.20有效地括号

上一篇:SSH:dataSource配置问题


下一篇:js正则表达式的使用