20. 有效的括号
public boolean isValid(String s) {
// 自己的做法,遇见'{' 入'{'
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if ((ch == '[' || ch == '{') || ch == '(') {
stack.push(ch);
} else if (!stack.isEmpty()) {
Character pop = stack.pop();
if (pop == '[' && ch == ']') {
continue;
} else if (pop == '{' && ch == '}') {
continue;
} else if (pop == '(' && ch == ')') {
continue;
}
return false;
} else {
return false;
}
}
if (!stack.isEmpty()) {
return false;
}
return true;
}
//==========================================================上面是自己的方法
// =========================================================-=下面是看了随想录后写的方法
public boolean isValid2(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == '(') {
stack.push(')');
} else if (ch == '{') {
stack.push('}');
} else if (ch == '[') {
stack.push(']');
} else if (stack.isEmpty()) {
return false;
} else {
if (ch != stack.pop()) {
return false;
}
}
}
return stack.isEmpty();
}
1047. 删除字符串中的所有相邻重复项
public String removeDuplicates(String s) {
ArrayDeque<Character> stack = new ArrayDeque<>();
char ch, peek = 0;
for (int i = 0; i < s.length(); i++) {
ch = s.charAt(i);
if (stack.isEmpty() || stack.peek() != ch) {
stack.push(ch);
} else {
stack.pop();
}
}
StringBuilder str = new StringBuilder();
while (!stack.isEmpty()) {
str.insert(0, stack.pop());
}
return str.toString();
}
150. 逆波兰表达式求值
public int evalRPN(String[] tokens) {
ArrayDeque<String> stack = new ArrayDeque<String>();
for (String token : tokens) {
if (isCal(token)) {
int var1 = Integer.parseInt(stack.pop());
int var2 = Integer.parseInt(stack.pop());
String var3 = null;
switch (token) {
//===================唯一 要注意的地方是 ,下面这个 var2 和 var1 的放置顺序
case "+":
var3 = String.valueOf(var2 + var1);
break;
case "-":
var3 = String.valueOf(var2 - var1);
break;
case "*":
var3 = String.valueOf(var2 * var1);
break;
case "/":
var3 = String.valueOf(var2 / var1);
break;
}
stack.push(var3);
continue;
}
stack.push(token);
}
assert stack.peek() != null;
return Integer.parseInt(stack.peek());
}
//====================小小的辅助函数
public boolean isCal(String str) {
return "+".equals(str) || "-".equals(str) || "*".equals(str) || "/".equals(str);
}
标签:ch,return,String,pop,else,表示法,就学,stack,过栈
From: https://www.cnblogs.com/Chain-Tian/p/16988521.html