`
plan454
  • 浏览: 7007 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
最近访客 更多访客>>
社区版块
存档分类
最新评论

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.

这是一道匹配题,最简单的方式就是用栈来做了,JAVA中有Strack类,所以直接用就可以了。
public boolean isValid(String s) {
        boolean result = false;
        List<Character> ls = new ArrayList<Character>();
        if(s == null || s.length()<2){
        	return false;
        }
        
        char[] chs = {'(',')','[',']','{','}'};
        for(char c : chs){
        	ls.add(c);
        }
        Stack<Character> st = new Stack<Character>();
        for(int i = 0 ;i<s.length();i++){
        	if(ls.contains(s.charAt(i))){
        			if(st.isEmpty()){
        				st.push(s.charAt(i));
        			}else{
        				/*System.out.println((char)st.peek());
        				System.out.println(s.charAt(i));
        				
        				System.out.println((char)st.peek()+s.charAt(i));*/
        				if((char)st.peek()+s.charAt(i) == 81 || (char)st.peek()+s.charAt(i) == 248 ||(char)st.peek()+s.charAt(i) == 184){
        					st.pop();
        				}else{
        					st.push(s.charAt(i));
        				}
        			}
        		
        	}
        }
        if(st.isEmpty()){
        	result = true;
        }else{
        	result = false;
        }
        
        
        return result;
    }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics