当前位置:网站首页>牛客网:表达式求值
牛客网:表达式求值
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];
}
};边栏推荐
猜你喜欢

Richard Behrman, the founder of dynamic planning

ADB is not an internal or external command, nor is it a runnable program or batch file

基于Feign远程调用

目标客户匹配数据表格成功案例展示

See how advanced technology changes human life

重庆第一个科创板IPO,来了

嘿!ONES 新星请看过来|师兄师姐说
Example analysis of SQL injection error reporting

软件项目管理 6.10.成本预算

新思科技助力以色列Visuality Systems推进安全“左移”
随机推荐
Snabbdom 虚拟 dom(一)
解决idea打开某个项目卡住的问题
Chongqing's first sci tech Innovation Board IPO is coming
vscode常用插件与配置
Who is using my server? what are you doing? when?
Fabric. JS zoom canvas
虚拟机ping不通的几种原因及解决办法
基于Feign远程调用
Fabric.js 元素被选中时保持原有层级
2022年茶艺师(中级)操作证考试题库及模拟考试
Mysql database implementation setting field length
厉害了,工信部推出 “一键解绑” 手机号绑定的互联网账号,堪称神器
fail-fast和fail-safe
For more than 20 years, there are only Durex, Okamoto and jasbon in the condom market
AHK common functions
What is the highest compound interest insurance product? How much does it cost a year?
期货账户资金安全吗?
flex布局语法
二十多年了,安全套市场还只有杜蕾斯、冈本、杰士邦
Make good use of the industrial chain to attract investment, create industrial cluster effect and realize the coordinated development of industries