題目描述:
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and
empty spaces .
You may assume that the given expression is always valid.
Some examples:
"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23
Note: Do not use the eval built-in library function.
Hide Tags Stack Math
分析:
該題要實現一個帶有括號優先級的加減法計算器,實質就是棧的使用。不多說了,直接看代碼註釋吧
/**///////////////////////56ms//*/
class Solution {
public:
int docompute(int a,int b,char opd){ //計算a opera b
if(opd == '+')
return a + b;
if(opd == '-')
return a - b;
}
bool isopd(char ch){ //判斷是否是運算符
return (ch == '+' || ch == '-' || ch == '(' || ch == ')'||ch == '=');
}
int calculate(string s) {
int len = s.size();
if(len == 0)
return 0;
s.push_back('='); //在表達式末尾加上'=',方便判斷是否計算結束
stack<char> opd;
opd.push('='); //在運算符棧底添加'=',方便判斷是否計算結束
stack<int> num; //操作數棧
int i = 0;
while( i <= len){
if(isdigit(s[i])){ // 如果是數字字符,則轉換爲整數後壓入操作數棧。注意處理多位數的情況
int dat = 0;
while(isdigit(s[i])){
dat = dat * 10 + (s[i]-'0');
i++;
}
num.push(dat);
}
else if(isopd(s[i])){ //如果是運算符
if(s[i] == '('){ '('直接壓入棧
opd.push(s[i]);
i++;
continue;
}
if(s[i] == ')'){
//遇到')'時,需判斷棧頂運算符是'+'或'-',直接取出計算後將結果要入操作數棧;
//否則只能是'(',彈出棧.
//繼續處理下一個字符
char oper = opd.top();
opd.pop();
if(oper == '+' || oper == '-'){
int a = 0, b = 0;
b = num.top();
num.pop();
a = num.top();
num.pop();
int re = docompute(a,b,oper);
num.push(re);
opd.pop(); //pop teh '('
}
i++;
continue;
}
if(s[i] == '+' || s[i] == '-'){ //遇到'+'或‘-’,看運算符棧頂
char oper = opd.top();
if(oper == '=' || oper == '('){ //若運算符棧頂是'='或'(',直接將當前運算符壓入棧
opd.push(s[i]);
i++;
continue;
}
else{ //棧頂爲'+'或'-',取出計算
opd.pop();
int a = 0, b = 0;
b = num.top();
num.pop();
a = num.top();
num.pop();
int re = docompute(a,b,oper);
num.push(re);
continue;
}
}
if(s[i]=='='){ //遇到'=',
if(opd.top() == '=') //棧頂也是'=',表示計算結束,返回結果
return num.top();
else{ //不是等於,表明還有運算符,且只能是'+'或'-',取出計算結果
char oper = opd.top();
opd.pop();
int a = 0, b = 0;
b = num.top();
num.pop();
a = num.top();
num.pop();
int re = docompute(a,b,oper);
//cout << re << endl;
num.push(re);
continue;
}
}
}
else //跳過空格
i++;
}
}
};