首页 > 其他 > 详细

leetcode : valid parenttheses

时间:2017-02-14 11:58:36      阅读:307      评论:0      收藏:0      [点我收藏+]

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.

 

tag : stack, string

注意: hashmap。 map.keySet().contains(key). map.values().contains(value) 方法

public class Solution {
    public boolean isValid(String s) {
        
        if(s == null || s.length() == 0){
            return true;
        }
        
        if(s.length() % 2 != 0){
            return false;
        }
        
        HashMap<Character,Character> map = new HashMap<Character,Character>();
        map.put(‘(‘,‘)‘);
        map.put(‘[‘,‘]‘);
        map.put(‘{‘,‘}‘);
        Stack<Character> stack = new Stack<Character>();
        
        for(int i = 0; i < s.length(); i++){
            char cur = s.charAt(i);
            if(map.keySet().contains(cur)){
                stack.push(cur);
            }else if(map.values().contains(cur)){
                if(!stack.isEmpty() && map.get(stack.peek()) == cur){
                    stack.pop();
                }else{
                    return false;
                }
            }
        }
        
        return stack.isEmpty();
  
    }
}

 

leetcode : valid parenttheses

原文:http://www.cnblogs.com/superzhaochao/p/6396716.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!