代码随想录算法训练营Day11|栈与队列part02
一、20. 有效的括号
这一题就比较简单
class Solution {
public boolean isValid(String s) {
Stack<Character> st=new Stack<>();
char c;
for(int i=0;i<s.length();i++){
c=s.charAt(i);
if(c=='('){
st.push(')');
}
else if(c=='{'){
st.push('}');
}
else if(c=='['){
st.push(']');
}
else if (st.isEmpty() || st.peek() != c) {
return false;
}
else {//如果是右括号判断是否和栈顶元素匹配
st.pop();
}
}
return st.isEmpty();
}
}
二、1047. 删除字符串中的所有相邻重复项
class Solution {
public String removeDuplicates(String s) {
Stack<Character> st=new Stack<>();
char c;
for(int i=0;i<s.length();i++){
c=s.charAt(i);
if(st.isEmpty()|| st.peek()!=c){
st.push(c);
}
else{
st.pop();
}
}
//剩余的元素即为不重复的元素
String str = "";
while (!st.isEmpty()) {
str = st.pop() + str;
}
return str;
}
}
三、 150. 逆波兰表达式求值
使用逆波兰求值可以避免运算符优先级出错的问题,就是要注意“-”和“/”的时候要注意。
class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> stack = new LinkedList();
for (String s : tokens) {
if ("+".equals(s)) {
stack.push(stack.pop() + stack.pop());
// 注意 - 和/ 需要特殊处理
} else if ("-".equals(s)) {
stack.push(-stack.pop() + stack.pop());
} else if ("*".equals(s)) {
stack.push(stack.pop() * stack.pop());
} else if ("/".equals(s)) {
int temp1 = stack.pop();
int temp2 = stack.pop();
stack.push(temp2 / temp1);
} else {
stack.push(Integer.valueOf(s));
}
}
return stack.pop();
}
}