一、 20. 有效的括號
題目鏈接:https://leetcode.cn/problems/valid-parentheses/
思路:遇到“( { [” 將對應的 ”)}]“的字符壓入棧中,遇到”)}]“字符的時候,判斷棧是否為空,為空直接俄返回false?;蛘卟粸榭蘸蜅m?shù)脑夭幌嗤卜祷豧alse,最后判斷是棧是否為空
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
stack.push(')');
} else if (c == '{') {
stack.push('}');
} else if (c == '[') {
stack.push(']');
} else {
if (stack.isEmpty()) {
return false;
}
if (stack.pop() != c) {
return false;
}
}
}
return stack.isEmpty();
}
}
二、 1047. 刪除字符串中的所有相鄰重復項
題目鏈接:https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/
思路一:使用棧結構,棧不為空并且棧頂元素和當前元素相等的話,就彈出棧頂元素,反之加入到棧中。然后遍歷棧放入到str結果集中,注意棧是倒序的
class Solution {
public String removeDuplicates(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!stack.isEmpty() && stack.peek() == c) {
stack.pop();
} else {
stack.push(c);
}
}
String result = "";
while (!stack.isEmpty()) {
result = stack.pop() + result;
}
return result;
}
}
思路二、使用stringBuffer模擬棧,如果棧不為空,并且棧頂元素和當前元素相同,則彈出棧頂元素,反之,則加入元素
class Solution {
public String removeDuplicates(String s) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
int len = result.length();
if (len != 0 && result.charAt(len - 1) == c) {
result.deleteCharAt(len - 1);
} else {
result.append(c);
}
}
return result.toString();
}
}
三、150. 逆波蘭表達式求值
題目鏈接:https://leetcode.cn/problems/evaluate-reverse-polish-notation/
思路:遇到+ - * / 字符串時候,stack.push(stack.pop() + stack.pop());注意 - /是前一個數(shù)-or/后一個數(shù)
遇到數(shù)字直接stack.push(數(shù)字);
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < tokens.length; i++) {
String str = tokens[i];
if ("+".equals(str)) {
stack.push(stack.pop() + stack.pop());
} else if ("-".equals(str)) {
int temp = stack.pop();
stack.push(stack.pop() - temp);
} else if ("*".equals(str)) {
stack.push(stack.pop() * stack.pop());
} else if ("/".equals(str)) {
int temp = stack.pop();
stack.push(stack.pop() / temp);
} else {
stack.push(Integer.parseInt(str));
}
}
return stack.pop();
}
}