问题描述:给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。有效字符串需满足
1)左括号必须用相同类型的右括号闭合
2)左括号必须以正确的顺序闭合
3)空字符
例:输入: “()”
输出: true
思路:简单题,直接使用栈,左括号直接入栈,遇到右括号时判断括号是否匹配,匹配则将栈顶元素出栈,继续匹配;否则失败。
class Solution {
public boolean isValid(String s) {
if(s == null || s.length() == 0)
return true;
Deque<Character> stack = new ArrayDeque<>();
char[] cstr = s.toCharArray();
for(int i = 0; i < cstr.length; ++i){
if(cstr[i] == ')' || cstr[i] == ']' || cstr[i] == '}'){
if(stack.isEmpty()){
return false;
} else if((cstr[i] == '}' && stack.peek() == '{') || (cstr[i] == ')' && stack.peek() == '(') || (cstr[i] == ']' && stack.peek() == '[')){
stack.pop();
}else{
return false;
}
}else{
stack.push(cstr[i]);
}
}
if(stack.isEmpty())
return true;
return false;
}
}
//更优雅的代码
class Solution {
public boolean isValid(String s) {
if(s == null || s.length() == 0)
return true;
Deque<Character> stack = new ArrayDeque<>();
char[] cstr = s.toCharArray();
//在栈中插入一个辅助元素(保证栈中至少有一个元素,不会出现访问栈顶发生空指针异常的情况)
stack.push('*');
for(int i = 0; i < cstr.length; ++i){
if(cstr[i] == '('){
stack.push(')');
}else if(cstr[i] == '{'){
stack.push('}');
}else if(cstr[i] == '['){
stack.push(']');
}else if(stack.pop() != cstr[i]){
//一旦栈顶元素与右括号不等,说明匹配失败
return false;
}
}
//是否只剩下辅助元素*
return stack.size() == 1;
}
}