1.删除字符串中的所有相邻重复项
可以用数组模拟栈结构
class Solution {
public String removeDuplicates(String s) {
if(s.length()<=1){
return s;
}
StringBuffer ret=new StringBuffer();
for(int i=0;i<s.length();i++){
if(ret.length()<1){
ret.append(s.charAt(i));
}else if(s.charAt(i)==ret.charAt(ret.length()-1)){
ret.deleteCharAt(ret.length()-1);
}else{
ret.append(s.charAt(i));
}
}
return ret.toString();
}
}
2.比较含退格的字符串
844. 比较含退格的字符串 - 力扣(LeetCode)
class Solution {
public boolean backspaceCompare(String s, String t) {
return changeStr(s).equals(changeStr(t));
}
public String changeStr(String str1){
StringBuffer ss=new StringBuffer();
char[] str=str1.toCharArray();
for(char ch:str){
if(ch!='#'){
ss.append(ch);//入栈
}else{
if(ss.length()>0){
ss.deleteCharAt(ss.length()-1);//出栈
}
}
}
return ss.toString();
}
}
3.基本计算器2
. - 力扣(LeetCode)
算法原理
双端队列也可以实现栈
class Solution {
public int calculate(String s) {
//双端队列,实现栈操作
Deque<Integer> deque=new ArrayDeque<>();
char op='+';
int i=0,n=s.length();
char[] ss=s.toCharArray();
while(i<n){
//1.先考虑为空的情况
if(ss[i]==' '){
i++;
}else if(ss[i]>='0'&ss[i]<='9'){
int tmp=0;
while(i<n&&ss[i]>='0'&ss[i]<='9'){
tmp=tmp*10+(ss[i]-'0');
i++;
}
if(op=='+'){
deque.push(tmp);
}else if(op=='-'){
deque.push(-tmp);
}else if(op=='*'){
deque.push(deque.poll()*tmp);
}else if(op=='/'){
deque.push(deque.poll()/tmp);
}
}else{
op=ss[i];
i++;
}
}
//遍历队列
int ret=0;
while(!deque.isEmpty()){
ret=ret+deque.poll();
}
return ret;
}
}
4.字符串解码
394. 字符串解码 - 力扣(LeetCode)
算法原理
class Solution {
public String decodeString(String s) {
int i=0,n=s.length();
char[] ss=s.toCharArray();
//构造栈
Stack<StringBuffer> strstack=new Stack<>();
//字符串要先加入一个空字符串
//不然会出现越界的情况
strstack.push(new StringBuffer());
Stack<Integer> numstack=new Stack<>();
while(i<n){
//1.遇到数字的情况
if(ss[i]>='0'&&ss[i]<='9'){
int tmp=0;
while(i<n&&ss[i]>='0'&&ss[i]<='9'){
tmp=tmp*10+(ss[i]-'0');
i++;
}
numstack.push(tmp);
}else if(ss[i]==' '){
i++;
}else if(ss[i]=='['){
i++;
//后面遇到的字符串都要加入栈中
StringBuffer str=new StringBuffer();
while(i<n&&ss[i]>='a'&&ss[i]<='z'){
str.append(ss[i]);
i++;
}
strstack.push(str);
}else if(ss[i]==']'){
int num1=numstack.pop();
StringBuffer str1=strstack.pop();
while(num1--!=0){
strstack.peek().append(str1);
}
i++;
}else{
//后面遇到的字符串都要加入栈中
StringBuffer str=new StringBuffer();
while(i<n&&ss[i]>='a'&&ss[i]<='z'){
str.append(ss[i]);
i++;
}
strstack.peek().append(str);
}
}
return strstack.peek().toString();
}
}
5.验证栈序列
. - 力扣(LeetCode)
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> st = new Stack<>();
int i = 0, n = popped.length;
for (int x : pushed) {
st.push(x);
while (!st.isEmpty() && st.peek() == popped[i]) {
st.pop();
i++;
}
}
return i == n;
}
}