20. 有效的括号
作者:
Andysys | 来源:发表于
2019-12-29 00:21 被阅读0次 private Map<Character, Character> mappings;
private Stack<Character> stack;
{
mappings = new HashMap<>();
mappings.put(')', '(');
mappings.put('}', '{');
mappings.put(']', '[');
stack = new Stack<>();
}
public boolean isValid(String s) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (mappings.containsKey(c)) {
char top = stack.empty() ? '#' : stack.pop();
if (top != mappings.get(c)) {
return false;
}
} else {
stack.push(c);
}
}
return stack.empty();
}
本文标题:20. 有效的括号
本文链接:https://www.haomeiwen.com/subject/odbeoctx.html
网友评论