检测括号的有效性
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
package com.lhb.offer; import java.util.Deque; import java.util.LinkedList; /** * @author lhb * @date 2022/3/18 */ public class Offer_20 { public static boolean isValid(String s ) { Deque<Character> stack = new LinkedList<>(); for (char c : s.toCharArray()) { if (c == '(') { stack.push(')'); } else if (c == '[') { stack.push(']'); } else if (c == '{') { stack.push('}'); } else if (stack.isEmpty() || c != stack.pop()) { return false; } } return stack.isEmpty(); } public static void main(String[] args) { System.out.println(isValid("()()()(){}{}{}{}[][][]["));// false } }

浙公网安备 33010602011771号