这里写目录标题
20. 有效的括号
一道简单的题目,考察栈的基本用法。要判断字符串里的括号是否都能匹配成功,我们只需遍历字符串,依次把左括号入栈,当遍历到右括号时,就把栈顶元素出栈,判断是否与右括号对应。
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
char ch;
Map<Character,Character> map = new HashMap<>();
map.put('(',')');
map.put('{','}');
map.put('[',']');
for(int i = 0; i < s.length(); i++){
ch = s.charAt(i);
if(ch == '(' || ch == '{' || ch == '['){ //如果是左括号则入栈
stack.push(ch);
}else if(stack.isEmpty() || ch != map.get(stack.peek())){ //如果栈不为空或栈顶元素与当前括号不匹配,直接返回false
return false;
}else{ //栈顶元素与当前遍历元素匹配,出栈
stack.pop();
}
}
return stack.isEmpty();
}
}
1047. 删除字符串中的所有相邻重复项
使用Stack作为栈
class Solution {
public String removeDuplicates(String s) {
Stack<Character> stack = new Stack<>();
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if(!stack.isEmpty() && stack.peek() == ch){
stack.pop();
}else{
stack.push(ch);
}
}
String res = "";
while(!stack.isEmpty()){
res = stack.pop() + res;
}
return res;
}
}
直接用StringBuilder作为栈
使用StringBuilder作为栈,就可以省去组装字符串那一步
class Solution {
public String removeDuplicates(String s) {
StringBuilder res = new StringBuilder();
int top = -1; //res的长度
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(top >= 0 && res.charAt(top) == c){ //如果res字符串内有字符,且最后一位和当前s遍历到的元素相同
res.deleteCharAt(top);
top--;
}else{
res.append(c);
top++;
}
}
return res.toString();
}
}
150. 逆波兰表达式求值
class Solution {
public int evalRPN(String[] tokens) {
ArrayDeque<Integer> expl = new ArrayDeque<>();
for(String s : tokens){
if(s.equals("+")){
expl.push(expl.pop() + expl.pop());
}else if(s.equals("-")){
expl.push(-expl.pop() + expl.pop()); //对于-和/要特殊处理
}else if(s.equals("*")){
expl.push(expl.pop() * expl.pop());
}else if(s.equals("/")){
int temp1 = expl.pop();
int temp2 = expl.pop();
expl.push(temp2 / temp1);
}else{
expl.push(Integer.valueOf(s));
}
}
return expl.pop();
}
}