前言
三道题目都是使用栈
解决的经典题目,难度都不大。
我觉得最主要就是如何把思路用代码实现,写出相应的代码。
比如有效的括号,当遇到左括号时直接压入一个对应的右括号,这样在遇到右括号时,直接比对栈顶元素即可。这样实现代码非常简洁。
再比如 删除字符串中的所有相邻重复项,直接使用一个字符串str作为栈,代码实现同样非常简洁。
这样的思路可能做的多了自然就会想到。
20. 有效的括号
使用栈解决有效括号,注意栈为空时的判断。
public class LC20_isValid {
public boolean isValid(String s) {
Deque<Character> st = new ArrayDeque<>();
// 如果遇见左括号就压入一个对应的右括号,
// 遇见右括号,就弹出一个栈顶元素比对
for (int i = 0; i < s.length(); i++) {
if ('(' == s.charAt(i)) st.push(')');
else if (s.charAt(i) == '{') st.push('}');
else if (s.charAt(i) == '[') st.push(']');
else {
if (st.isEmpty()) return false;
if (st.pop() != s.charAt(i)) {
return false;
}
}
}
return st.isEmpty();
}
}
1047. 删除字符串中的所有相邻重复项
public class LC1047_removeDuplicates {
public static void main(String[] args) {
LC1047_removeDuplicates s = new LC1047_removeDuplicates();
System.out.println(s.removeDuplicates("abbaca"));
}
public String removeDuplicates(String s) {
Deque<Character> st = new ArrayDeque<>();
st.push(s.charAt(0));
for (int i = 1; i < s.length(); i++) {
if (st.isEmpty() || st.peek() != s.charAt(i)) {
st.push(s.charAt(i));
} else {
st.pop();
}
}
String res = "";
while (!st.isEmpty()) {
res = st.pop() + res;
}
return res;
}
// StringBuilder作为栈
public String removeDuplicates2(String s) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (str.length() == 0 || str.charAt(str.length() - 1) == s.charAt(i)) {
str.append(s.charAt(i));
} else {
str.deleteCharAt(str.length() - 1);
}
}
return str.toString();
}
}
1048. 逆波兰表达式求值
public class LC150_evalRPN {
public static void main(String[] args) {
LC150_evalRPN s = new LC150_evalRPN();
String[] tokens = new String[]{"2","1","+","3","*"};
System.out.println(s.evalRPN(tokens));
}
public int evalRPN(String[] tokens) {
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < tokens.length; i++) {
String x = tokens[i];
if (x.equals("+")) {
stack.push(stack.pop() + stack.pop());
} else if (x.equals("-")) {
stack.push( - stack.pop() + stack.pop());
} else if (x.equals("*")) {
stack.push(stack.pop() * stack.pop());
} else if (x.equals("/")) {
int x1 = stack.pop();
int x2 = stack.pop();
stack.push(x2 / x1);
} else {
stack.push(Integer.valueOf(tokens[i]));
}
}
return stack.pop();
}
}