20. 有效的括号 - LeetCode
20. 有效的括号
栈
class Solution {
public boolean isValid(String s) {
Map<Character, Character> map = new HashMap<>();
map.put(')', '(');
map.put(']', '[');
map.put('}', '{');
Stack<Character> stack = new Stack<>();
for(char c : s.toCharArray())
if(map.containsKey(c)){
if(stack.isEmpty()) return false;
if(map.get(c) != stack.pop()) return false;
} else stack.push(c);
return stack.isEmpty();
}
}
- 用HashMap存储对应的括号,用栈来匹配括号

浙公网安备 33010602011771号