题目如下:
给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
我的代码:
class Solution {
private static Map<Character, Character> map = new HashMap<>();
static {
map.put(')', '(');
map.put(']', '[');
map.put('}', '{');
}
public boolean isValid(String s) {
//不成对,直接返回错误
if (s.length() % 2 == 1)
return false;
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
Character c2 = map.get(c);
//1.找不到说明是左符号,压入栈中;2.找的到与栈顶对比
if (c2 == null) {
stack.push(c);
} else if (stack.isEmpty() || c2 != stack.pop()) {
return false;
}
}
//注意这里,判断栈内数据是否为空,一开始这里直接反回了true,当输入内容为"(("判断出错。
return stack.isEmpty();
}
}