题目:判断括号是否对称

题目:

判断括号是否对称
给定一个值包括’(’、’)’、’[’、’]’、’{’、’}'的字符串,判断字符串是否有效。
有效字符串需满足:
1、左括号必须用相同类型的右括号闭合。
2、左括号必须以正确的顺序闭合。
注意空字符串可别认为是有效字符串

答案:

public class Test {
    public static void main(String[] args) {
        // 测试代码
        System.out.println(isDuiCheng("{}[]"));
        System.out.println(isDuiCheng("{[]}"));
        System.out.println(isDuiCheng("[{]}"));
    }

    // 判断是否符合条件要求
    private static boolean isDuiCheng(String s) {

        // 用于判断里面是否有()[]{}
        int count = 0;

        // 创建栈对象
        Stack<Integer> stack = new Stack<>();

        // 遍历字符串中的每一个字符
        for (int i = 0; i < s.length(); i++) {
            // 获取字符串中的字符
            char c = s.charAt(i);

            // 获取字符所代表的数字
            int number = number(c);

            // 如果字符是(、[、{中的任意一个
            if (number < 0) {
                count++;
                // 把(、[、{放进栈里面
                stack.push(number);
            } else if (number > 0) {
                count++;
                // 如果栈里面没有(、[、{,那就直接返回false
                if (stack.isEmpty()) return false;
                // 如果栈顶的字符和该字符不对应,那就直接返回false
                if (number + stack.peek() != 0) return false;
                // 如果栈顶的字符和该字符对应,那就移除栈顶字符
                stack.pop();
            }
        }

        // 如果字符串里面有()[]{},并且栈不是空的,那就直接返回true
        return count != 0 && stack.isEmpty();
    }

    // 把()[]{}变成相应的数字,便于判断和比较
    private static int number(char c) {
        switch (c) {
            case '(':
                return -1;
            case ')':
                return 1;
            case '[':
                return -2;
            case ']':
                return 2;
            case '{':
                return -3;
            case '}':
                return 3;
            default:
                return 0;
        }
    }
}

结果:

true
true
false
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值