20 力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
有点像学数据结构时老师举得例子。遍历s,如果遇到的是(/[/{,则入栈)/]/},如果遇到的是)/]/},若相等则出栈,不相等就说明不配套。如果stack始终为空,说明肯定没有配套的。最后看栈是否清空了。
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
Character charStr = s.charAt(i);
if(charStr == '('){
stack.push(')');
}else if(charStr == '['){
stack.push(']');
}else if(charStr == '{'){
stack.push('}');
}else if(stack.isEmpty() || charStr != stack.pop()){
return false;
}
}
return stack.isEmpty();
}
}
1047.删除字符串中的所有相邻重复项
我自己堆栈的方法:
class Solution {
public String removeDuplicates(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
if(stack.isEmpty()){
stack.push(s.charAt(i));
}
else{
if(s.charAt(i) == stack.peek()){
stack.pop();
}else{
stack.push(s.charAt(i));
}
}
}
StringBuilder result = new StringBuilder();
for (Character character : stack) {
result.append(character);
}
return result.toString();
}
}
150.力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
比较简单
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for(int i = 0; i<tokens.length;i++){
if(tokens[i].equals("+")){
Integer s1 = stack.pop();
Integer s2 = stack.pop();
stack.push(s2 + s1);
}else if(tokens[i].equals("-")){
Integer s1 = stack.pop();
Integer s2 = stack.pop();
stack.push(s2 - s1);
} else if (tokens[i].equals("/")) {
Integer s1 = stack.pop();
Integer s2 = stack.pop();
stack.push(s2 / s1);
} else if (tokens[i].equals("*")) {
Integer s1 = stack.pop();
Integer s2 = stack.pop();
stack.push(s2 * s1);
}else{
stack.push(Integer.parseInt(tokens[i]));
}
}
return stack.pop();
}
}