示例 1:
输入: "()" 输出: true
示例 2:
输入: "()[]{}" 输出: true
示例 3:
输入: "(]" 输出: false
示例 4:
输入: "([)]" 输出: false
示例 5:
输入: "{[]}" 输出: true
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
Stack<Character> invstack = new Stack<>();
if(s.length() == 0)
return true;
for(int i =0; i < s.length(); i++){
stack.push(s.charAt(i));
}
while(!stack.isEmpty() && s.length() != 1){
if(!invstack.isEmpty()){
if(stack.peek() == '(' && invstack.peek() == ')' ){
stack.pop();
invstack.pop();
}
else if(stack.peek() == '{' && invstack.peek() == '}' ){
stack.pop();
invstack.pop();
}
else if(stack.peek() == '[' && invstack.peek() == ']'){
stack.pop();
invstack.pop();
}
else invstack.push(stack.pop());
if(invstack.isEmpty() && stack.isEmpty())
return true;
}
else invstack.push(stack.pop());
}
return false;
}
}
思路:
定义两个栈,栈一存储输入字符串,如(){}[], 栈底为(, 栈顶为]
栈二为栈一的出栈存储。如果两个栈顶元素相同则此时栈一和栈二同时出栈。
注意:1.当为“”返回值为TRUE
2.当为 “((”时如果不限制栈二此时不为空,将导致(stack.peek() == invstack.peek())判断出错