栈的介绍和使用(算法)

栈最大的特点是先进先出。利用这个特点应用于我们的日常生活会有很大的便利。下面我们一起来看看吧。

class Solution {

public:

int calculate(string s) {

//用数组来模拟栈

vector<int> st;

int i=0,n=s.size();

char op='+';

while(i<n){

if(si==' ') i++;

else if(si>='0'&&si<='9'){

int tmp=0;

while(i<n&&si>='0'&&si<='9')

tmp=tmp*10+(si++-'0');

if(op=='+') st.push_back(tmp);

else if(op=='-') st.push_back(-tmp);

else if(op=='*') st.back()*=tmp;

else st.back()/=tmp;

}else{

op=si;

i++;

}

}

int sum=0;

for(auto e: st){

sum+=e;

}

return sum;

}

};

class Solution {

public:

string decodeString(string s) {

stack<int> nums;

stack<string> st;

st.push("");

int i=0,n=s.size();

while(i<n){

if(si>='0'&&si<='9'){

int tmp=0;

while(si>='0'&&si<='9'){

tmp=tmp*10+(si++-'0');

}

nums.push(tmp);

}else if(si=='['){

i++;

string tmp="";

while(si>='a'&&si<='z'){

tmp+=si++;

}

st.push(tmp);

}else if(si==']'){

string tmp=st.top();

st.pop();

int k=nums.top();

nums.pop();

while(k--){

st.top()+=tmp;

}

i++;

}else{

string tmp;

while(i<n&&si>='a'&&si<='z'){

tmp+=si++;

}

st.top()+=tmp;

}

}

return st.top();

}

};

class Solution {

public:

bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {

int n=popped.size();

stack<int> result;

int i=0;

for(auto e: pushed){

result.push(e);

while(result.size()&&result.top()==poppedi){

result.pop();

i++;

}

}

return i==n;

}

};

相关推荐
玩转单片机与嵌入式12 分钟前
深入浅出TinyML 36:如何验证一个TinyML系统真正具备工程应用价值?
网络·人工智能·算法
傲世仙尊1 小时前
环形链表找入环点-从相遇到等距的最后一推
数据结构·链表
Nazarick2 小时前
力扣LeetCode热题75题(1)
java·算法·leetcode·力扣
16月6日-晴2 小时前
斐波那契数列题解
算法·leetcode
郝学胜-神的一滴3 小时前
Effective Python 条款47:吃透惰性属性
大数据·开发语言·数据库·人工智能·python·算法·oracle
Keven_114 小时前
算法札记:有限差分
算法
忙里偷闲学python4 小时前
GK2A 林火蔓延预报算法说明
算法
我是伪码农4 小时前
11.21程序设计
数据结构·算法
Tisfy5 小时前
LeetCode 3561.移除相邻字符:栈(相邻相消)
算法·leetcode·字符串·题解·栈·相邻相消
战6175 小时前
Python 基础算法:三种排序、二分查找与递归
开发语言·python·算法