JasonChang

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

use stack (be careful of empty stack)

 1 public class Solution {
 2     public boolean isValid(String s) {
 3         // IMPORTANT: Please reset any member data you declared, as
 4         // the same Solution instance will be reused for each test case.
 5         if(s == null||s.length() == 0)
 6             return true;
 7             
 8         Stack<Character> mystack = new Stack<Character>();
 9         char[] mychar = s.toCharArray();
10         for(int i = 0; i < mychar.length; i++)
11         {
12             if(mychar[i] == '('||mychar[i] == '{'||mychar[i] == '[')
13                 mystack.push(mychar[i]);
14             else if(mychar[i] == ')')
15             {
16                 if(mystack.isEmpty() || mystack.pop() != '(')
17                     return false;
18             }
19             else if(mychar[i] == ']')
20             {
21                 if(mystack.isEmpty() || mystack.pop() != '[')
22                     return false;
23             }
24             else if(mychar[i] == '}')
25             {
26                 if(mystack.isEmpty() || mystack.pop() != '{')
27                     return false;
28             }
29             else
30                 return false;
31         }
32         if(mystack.isEmpty())
33             return true;
34         return false;
35         
36     }
37 }

 

 

posted on 2013-11-05 11:54  JasonChang  阅读(169)  评论(0编辑  收藏  举报