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     public boolean isValid(String s) {
 3         // Note: The Solution object is instantiated only once and is reused by each test case.
 4         // '(' - '0' :: -8
 5         // ')' - '0' :: -7
 6         
 7         // '[' - '0' :: 43
 8         // ']' - '0' :: 45
 9         
10         // '{' - '0' :: 75
11         // '}' - '0' :: 77
12         Stack<Integer> st = new Stack<Integer>();
13         for(int i = 0; i < s.length(); i ++){
14             int c = s.charAt(i) - '0';
15             if(c == -8 || c == 43 || c == 75) st.push(c);
16             else if(c == -7){
17                 if(st.size() != 0 && st.peek() == -8)st.pop();
18                 else return false;
19             }
20             else if(c == 45){
21                 if(st.size() != 0 && st.peek() == 43)st.pop();
22                 else return false;
23             }
24             else if(c == 77){
25                 if(st.size() != 0 && st.peek() == 75)st.pop();
26                 else return false;
27             }
28             else return false;
29         }
30         if(st.size() != 0) return false;
31         return true;
32     }
33 }

 

第三遍:

 1 public class Solution {
 2     public boolean isValid(String s) {
 3         LinkedList<Character> ll = new LinkedList<Character>();
 4         if(s == null || s.length() == 0) return false;
 5         for(int i = 0; i < s.length(); i ++){
 6             if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') ll.push(s.charAt(i));
 7             else if(ll.size() == 0 || (s.charAt(i) == ')' && ll.peek() != '(') ||
 8             (s.charAt(i) == ']' && ll.peek() != '[') || (s.charAt(i) == '}' && ll.peek() != '{')) return false;
 9             else ll.pop();
10         }
11         return ll.size() == 0;
12     }
13 }

 

posted on 2014-08-06 10:51  Step-BY-Step  阅读(114)  评论(0编辑  收藏  举报

导航