Valid Parentheses(括号匹配)

解决思路:

1. 栈

2.使用Map,判断是否

 public boolean isValid(String s) {
        Stack<Character> parens = new Stack<>();
        
        Map<Character, Character> parenMap = new HashMap<>();
        parenMap.put('(', ')');
        parenMap.put('[', ']');
        parenMap.put('{', '}');
        
        
        for (int i = 0; i < s.length(); i++) {
            char paren = s.charAt(i);
            boolean isLeft = parenMap.containsKey(paren);
            
            
        
            if (isLeft) {
                parens.push(paren);
            } else {
                if (parens.empty()) {
                    return false;
                }

                char leftSide = parens.pop();
                if (parenMap.get(leftSide) != paren) {
                    return false;
                }
                
            
            }
        }
        
        return parens.empty();
    }

 

匹配

 

posted @ 2018-01-12 23:20  式微胡不归  阅读(130)  评论(0编辑  收藏  举报