📜  java代码示例中的平衡字符串

📅  最后修改于: 2022-03-11 14:52:08.058000             🧑  作者: Mango

代码示例2
public boolean isBalanced(String string) {
        HashMap bracketMap = new HashMap<>();
        bracketMap.put('(', ')');
        bracketMap.put('[', ']');
        bracketMap.put('{', '}');
        
        Stack stack = new Stack<>();
        
        for(int count = 0; count < string.length(); count++) {
            char current = string.charAt(count);
            
            if(bracketMap.keySet().contains(current)) {
                stack.push(current);
            } else if(bracketMap.values().contains(current)) {
                if(!stack.empty() && bracketMap.get(stack.peek()) == current){
                    stack.pop();
                } else {
                    return false;
                }
            }
        }
        return stack.empty();
    }