要求;
给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示列:
输入: "()"
输出: true
输入: "()[]{}"
输出: true
输入: "(]"
输出: false
输入: "([)]"
输出: false
输入: "{[]}"
输出: true
代码:
class Solution {
public boolean isValid(String s) {
Stack <Character> stack =new Stack<>();
Map<Character,Character> map= new HashMap<>();
map.put(')','(');
map.put('}','{');
map.put(']','[');
char[] chars= s.toCharArray();
for(char c:chars){
if(stack.isEmpty()){
//如果栈为空,直接压入栈
stack.push(c);
}else if(stack.peek()==map.get(c)){
//如果当前栈顶值和c对应则出栈
stack.pop();
}else {
stack.push(c);
}
}
return stack.isEmpty();
}
}