leetcode-cn 有效的括号

题目描述如图:
有效的括号
解法一:将待匹配的左括号放入队列或栈(因为只需拿最近一个元素并删除,用数组都行,只不过队列封装了removeLast(),所以直接用就好了)

private static boolean notMatch(char left, char right){
		return (left == '(' && right != ')') || (left == '[' && right != ']') || (left == '{' && right != '}');
	}

	private static boolean isValid(String s) {
		int length = s.length();
		if ("".equals(s)) {
			return true;
		}
		// 队列用来存左括号
		Deque<Character> bracketsIndex = new ArrayDeque<>();
		for (int i = 0; i < length; i++) {
			char c = s.charAt(i);
			if (c == '(' || c == '[' || c == '{') {
				bracketsIndex.add(c);
			} else if (!bracketsIndex.isEmpty() && (c == ')' || c == ']' || c == '}')) {
				if (notMatch(bracketsIndex.removeLast(), c)) {
					return false;
				}
			} else {
				return false;
			}

		}

		// 确保入队列的左括号都被消费掉
		return bracketsIndex.isEmpty();
	}

解法二:将待匹配的左括号的索引放入队列,然后判断待匹配的左右括号的索引是否一个为奇数,另一个为偶数

	private static boolean oddAndEvenNumber(int leftIndex, int rightIndex){
		// 判断两个数是否同时为偶数或同时为奇数
		// 要使左右括号能够匹配上,必须满足:如果左括号索引为偶数,右括号索引则为奇数,反之亦然
		// 例如 {({}[])} 第一个"{"索引为0,与之匹配的最后一个索引必定为(length-1)奇数
		// 没明白的话,自己可以动手列举下,总结规律
		return ((leftIndex & 1) == 1) == ((rightIndex & 1) == 1);
	}
	
	private static boolean isValid(String s) {
		int length = s.length();
		if ("".equals(s)) {
			return true;
		}
		// 队列用来存左边括号的索引
		Deque<Integer> braceIndex = new ArrayDeque<>();
		Deque<Integer> bracketsIndex = new ArrayDeque<>();
		Deque<Integer> parenthesesIndex = new ArrayDeque<>();
		int lastIndex;
		for (int i = 0; i < length; i++) {
			char c = s.charAt(i);
			if (c == '(') {
				parenthesesIndex.add(i);
			} else if (c == '[') {
				bracketsIndex.add(i);
			} else if (c == '{') {
				braceIndex.add(i);
			} else if (c == ')' && !parenthesesIndex.isEmpty()) {
				// 以下三个 removeLast()调用的目的是取最近一个左括号的索引,用完得删除
				if (oddAndEvenNumber(parenthesesIndex.removeLast(), i)) {
					return false;
				}
			} else if (c == ']' && !bracketsIndex.isEmpty()) {
				if (oddAndEvenNumber(bracketsIndex.removeLast(), i)) {
					return false;
				}
			} else if (c == '}' && !braceIndex.isEmpty()) {
				if (oddAndEvenNumber(braceIndex.removeLast(), i)) {
					return false;
				}
			} else {
				return false;
			}

		}

		// 确保入队列的左括号的索引都被消费掉
		return braceIndex.isEmpty() && bracketsIndex.isEmpty() && parenthesesIndex.isEmpty();
	}

有效得括号

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值