public class Bracket { public static void main(String[] args) { String str = "[()]"; System.out.println(isValid(str)); } // [()] public static boolean isValid(String str) { Stack<Character> stack = new Stack<>(); Map<Character, Character> map = new HashMap<Character, Character>(); map.put(‘)‘, ‘(‘); map.put(‘}‘, ‘{‘); map.put(‘]‘, ‘[‘); char[] chs = str.toCharArray(); for (Character ch : chs) { if (!map.containsKey(ch)) { stack.push(ch); } else { Character item = map.get(ch); if (stack.isEmpty() || !item.equals(stack.pop())) { return false; } } } return stack.isEmpty(); } }
给定一个只包含字符’(’,’)’,’{’,’}’,’[‘和’]'的字符串,判断输入字符串是否有效
原文地址:https://www.cnblogs.com/moris5013/p/11640869.html
时间: 2024-10-10 21:17:27