当前位置:网站首页>牛客网:表达式求值
牛客网:表达式求值
2022-06-10 16:42:00 【lsgoose】

计算表达式也是栈/递归的典型应用场景。
首先,如何处理运算符的优先级?乘号显然优先级更高,所以加号和减号运算的结果就直接压栈,直到遇到乘号就取出栈顶然后计算乘的结果再压栈,到最后返回时需要直接求和返回。
其次,我们如何来递归。我们要设置传入参数,这里设置两个参数:字符串和索引。
我们在函数主题中需要完成的任务有
1.如果是数字,需要循环算出数值大小
2.如果是左括号,则递归,这时返回的vector是两个数,一个是这个左括号对应右括号之间的所有项运算的结果,另外一个项是索引位,表示对应的右括号的索引的下一位
3.对运算符进行处理(一开始默认是加号),如果是加减,很明显直接压栈就行,乘则需要和栈顶元素进行运算再压栈
4.如果遇到右括号,则退出当前循环,对栈中元素求和后返回相应vector,否则将运算符更新(记录为当前元素)
代码如下所示:
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 返回表达式的值
* @param s string字符串 待计算的表达式
* @return int整型
*/
vector<int> function(string &s, int index){
stack<int> st;
char op='+';
int num=0;
int i=0;
for(i=index;i<s.length();++i){
if(isdigit(s[i])){
num=num*10+s[i]-'0';
if(i!=s.length()-1){
continue;
}
}else if(s[i]=='('){
vector<int> res=function(s, i+1);
num=res[0];
i=res[1];
if(i!=s.length()-1){
continue;
}
}
switch(op){
case '+':
st.push(num);
break;
case '-':
st.push(-num);
break;
case '*':
int temp=st.top();
st.pop();
st.push(temp*num);
}
num=0;
if(s[i]==')'){
break;
}else{
op=s[i];
}
}
int sum=0;
while(!st.empty()){
sum+=st.top();
st.pop();
}
return vector<int>{sum, i};
}
int solve(string s) {
return function(s, 0)[0];
}
};边栏推荐
- 2022年上海市安全员C证操作证考试题库模拟考试平台操作
- Accuracy of alphafold and NMR determination of protein structure in solution
- SOA architecture / test phase interface description language transformation scheme
- 路由器实验之serial接口的静态路由配置(补充)
- Swift 3pThread tool Promise Pipeline Master/Slave Serial Thread confinement Serial queue
- 大山深处的孩子,正在看见更远的星空
- 2022年焊工(初级)试题模拟考试平台操作
- 开源项目 PM 浅谈如何设计官网
- Eliminate if Five ways of else
- 仅需三步学会使用低代码ThingJS与森数据DIX数据对接
猜你喜欢

Detailed steps for installing redis image in docker (easy to understand, suitable for novices to get started quickly)

Graduation season: to you

B站不想成为“良心版爱优腾”

SOA架构/测试阶段接口描述语言转换方案

Xinsi technology helps Israel visuality systems promote the "left shift" of security

解决idea打开某个项目卡住的问题

二十多年了,安全套市场还只有杜蕾斯、冈本、杰士邦

HTML+PHP+Mysql登录注册页面

2022年T电梯修理考试题模拟考试题库及在线模拟考试

Web3最全搞钱秘籍,看这一篇就够了
随机推荐
Full link tracking & performance monitoring tool skywalking practice
丢失的遗传力--Missing heritability
Detailed derivation of perspective projection transformation and related applications
Fabric. Keep the original level when JS element is selected
关于透视投影变换及相关应用的详细推导
海外数据中心需要为不可预测的灾难做好准备
Fail fast and fail safe
Complete AHK function commands
【抬杠C#】如何实现接口的base调用
fail-fast和fail-safe
自定义视图:图形与图像的处理(一):使用简单图片
绘制混淆矩阵
C#_串口通信项目
2022G1工业锅炉司炉考题及在线模拟考试
每日一题-1287. 有序数组中出现次数超过25%的元素
com.netflix.client.ClientException: Load balancer does not have available server for client: userser
Example analysis of SQL injection error reporting
This article introduces you to j.u.c's futuretask, fork/join framework and BlockingQueue
Mysql database implementation setting field length
创建 Visual Studio 离线安装包并安装