给定一个只含小中大括号的字符串, 判断这个字符串的括号是否都是成对一起的.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); Map<Character, Character> map = new HashMap<>(); map.put('(', ')'); map.put('{', '}'); map.put('[', ']'); for (int i = 0; i < s.length(); i++) { char currentChar = s.charAt(i); if (map.containsKey(currentChar)) { stack.push(currentChar); } else if (stack.isEmpty() || map.get(stack.pop()) != currentChar) { return false; } } return stack.isEmpty(); } }
|