玩转数据结构(十二)括号匹配算法

/**
 * 基于栈实现--括号匹配算法
 */
public class BracketMarch {
    ArrayStack<Character> stack = new ArrayStack<Character>();

    public boolean isValid(String s) {
        for (int i = 0; i < s.length(); i++) {//[(]{)}
            char c = s.charAt(i);
            if(c == '{' || c == '[' || c == '(') {//将字符串中的所有左括号入栈
                stack.push(c);
            } else {
                if(stack.isEmpty()) {
                    return false;
                }

                char topChar = stack.pop();
                if(topChar == '{' && c != '}') {
                    return false;
                }
                if(topChar == '[' && c != ']') {
                    return false;
                }
                if(topChar == '(' && c != ')') {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        System.out.println(new BracketMarch().isValid("[]{}()"));
        System.out.println(new BracketMarch().isValid("[(]{)}"));
    }
}
结果:
true
false
 

猜你喜欢

转载自blog.csdn.net/zhoujian_liu/article/details/80915005