栈:平衡的字符串

前段时间面试华为时,考官问了一道小算法题。


微信图片_20200423223042.jpg

今天在看数据结构这本书时,想起了这道算法题。

其实就是使用栈这种数据结构判断一个中缀表达式中的分隔符,在这里做一个记录。

import java.util.Stack;

public class BalanceChecker {
    public boolean checkBlance(String expression) {
        boolean isBalanced = true;
        int characterCount = expression.length();
        Stack<Character> openDelimiterStack = new Stack<>();
        int index = 0;
        char nextCharacter = ' ';
        while (isBalanced && index < characterCount) {
            nextCharacter = expression.charAt(index);
            if (nextCharacter == '(' || nextCharacter == '[' || nextCharacter == '{') {
                openDelimiterStack.push(nextCharacter);
            } else {
                if (openDelimiterStack.empty()) {
                    isBalanced = false;
                } else {
                    Character openDelimiter = openDelimiterStack.pop();
                    isBalanced = isPaired(openDelimiter, nextCharacter);
                }
            }
            index++;
        }

        if (!openDelimiterStack.isEmpty())
            isBalanced = false;
        return isBalanced;
    }

    private boolean isPaired(Character open, Character close) {
        return (open == '(' && close == ')') ||
                (open == '[' && close == ']') ||
                (open == '{' && close == '}');
    }
}

推荐阅读更多精彩内容