有效的括号
问题:
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。 解析:
class Solution {
private HashMap<Character, Character> mappings;
public Solution() {
this.mappings = new HashMap<Character, Character>();
this.mappings.put(')', '(');
this.mappings.put('}', '{');
this.mappings.put(']', '[');
}
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
// 如果是右边的括号(闭)
if (this.mappings.containsKey(c)) {
// 压出栈中的一个左括号
char topElement = stack.empty() ? '#' : stack.pop();
// 进行对比
if (topElement != this.mappings.get(c)) {
return false;
}
} else {
//左括号则进栈
stack.push(c);
}
}
// 非空栈则说明有左括号没有匹配成功
return stack.isEmpty();
}
}
查看7道真题和解析
