题目链接:https://leetcode.cn/problems/valid-parentheses/description/
题目分析:使用栈实现,如果栈为空,直接入栈;如果栈不为空且栈顶元素与即将遍历字符匹配,则对应栈顶元素出栈;如不匹配,则对元素直接入栈
Java实现代码:
import java.util.Stack;
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public boolean isValid(String s) {
int length=s.length();
Stack strstack = new Stack<>();
for (int i = 0; i < length; i++) {
char thechar = s.charAt(i);
if(strstack.isEmpty()){
strstack.push(thechar);
continue;
}
char stacktop = strstack.peek();
if((thechar == ')' && stacktop == '(')||(thechar == '}' && stacktop == '{')||(thechar == ']' && stacktop == '[')){
strstack.pop();
}else {
strstack.push(thechar);
}
}
return strstack.isEmpty();
}
}
//leetcode submit region end(Prohibit modification and deletion)
题目链接:https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/description/
题目分析:与括号匹配思路一致 均属于消消消问题
Java实现代码:
class Solution {
public String removeDuplicates(String s) {
int leng = s.length();
Stack strstack = new Stack<>();
for (int i = 0; i < leng; i++) {
char thechar = s.charAt(i);
if(strstack.isEmpty()){
strstack.push(thechar);
continue;
}
if(strstack.peek() == thechar){
strstack.pop();
}else {
strstack.push(thechar);
}
}
String returnstr = "";
while (!strstack.isEmpty()){
returnstr = strstack.pop()+returnstr;
}
return returnstr;
}
}
题目链接:https://leetcode.cn/problems/evaluate-reverse-polish-notation/description/
主要是'逆向'--要注意其中的除法与减法计算
主要思路是:遇到符号---两次pop 运算后进行依次push;不是符号直接push
Java实现代码:
import java.util.Stack;
class Solution {
public int evalRPN(String[] tokens) {
Stack strstack = new Stack<>();
int size = tokens.length;
for (int i =0;i
_____________________________________________________________________________
今日补卡结束:对于栈与队列相关问题,主要是把握其'消消消'特性与顺序问题,想清楚能够使用时就很好写出题解;