leetcode 224.基本计算器
题干
实现一个基本的计算器来计算一个简单的字符串表达式 s 的值。
示例 1:
输入:s = “1 + 1”
输出:2
示例 2:
输入:s = " 2-1 + 2 "
输出:3
示例 3:
输入:s = “(1+(4+5+2)-3)+(6+8)”
输出:23
提示:
1 <= s.length <= 3 * 105
s 由数字、’+’、’-’、’(’、’)’、和 ’ ’ 组成
s 表示一个有效的表达式
题解
写一个getNumWithRightBound方法用来忽略空格获得数字,返回数字和该数字右界组成的pair
再写一个getPartialRes方法用来获得括号里的结果,如果遇到内部括号就递归,返回括号内结果和括号右界+1组成的pair
最后在原有的string s两侧加上左右括号,调用getPartialRes,直接起飞
也就是扫描字符串一遍,多了点中间变量
class Solution {
public:
pair<long long,int> getNumWithRightBound(string& s,int leftBound){
int n = s.length();
long long res = 0;
int index = leftBound;
while(index < n){
if(s[index] >= '0' && s[index] <= '9'){
res = res * 10 + s[index] - '0';
index++;
}else if(s[index] == ' ') index++;
else break;
}
return {res,index};
}
pair<long long,int> getPartialRes(string& s,int leftBound){
int n = s.length();
//bracketsMatch用来统计左右括号的对应关系
int bracketsMatch = 0;
//op用来存储符号
int op = 1;
long long res = 0;
int index = leftBound;
while(index < n){
if(s[index] == '('){
bracketsMatch++;
auto temp = getPartialRes(s,index + 1);
res += op * temp.first;
index = temp.second;
continue;
}
else if(s[index] == ')' && bracketsMatch == 0) break;
else if(s[index] == ')') bracketsMatch--;
else if(s[index] == '+') op = 1;
else if(s[index] == '-') op = -1;
else if(s[index] == ' '){
index++;
continue;
}else{
//遇到数字的情况
auto temp = getNumWithRightBound(s,index);
//cout<<temp.first<<' '<<temp.second<<endl;
res += op * temp.first;
index = temp.second;
continue;
}
index++;
}
return {res,index};
}
int calculate(string s) {
int n = s.length();
s = "(" + s + ")";
return getPartialRes(s,1).first;
}
};
其实也可以不用写这么多函数,直接从左到右一个个数字加也行,要注意的就是如果左括号左侧是负号,该括号内全部负号都要取反。