您的位置:首页 > 编程语言 > C语言/C++

leetcode 日经贴,Cpp code -Basic Calculator

2015-06-11 18:52 621 查看
Basic Calculator

class Solution {
private:
char token;
int pos, num;
stack<char> ops;
stack<int> vals;
int getpriority(char op) {
int ret = 0;
switch(op) {
case '(': ret = 4; break;
case '+':
case '-': ret = 2; break;
case ')': ret = 1; break;
case 'd': ret = 0; break;
default: ret = -1; break;
}
return ret;
}
void next_token(const string &s) {
while (pos < s.length() && s[pos] == ' ') {
++pos;
}
if (pos >= s.length()) {
token = '$';
} else if (s[pos] < '0' || s[pos] > '9') {
token = s[pos];
++pos;
} else {
token = 'd';
num = 0;
while (pos < s.length() && s[pos] >= '0' && s[pos] <= '9') {
num = num * 10 + int(s[pos++] - '0');
}
}
}
public:
int calculate(string s) {
while (!ops.empty()) {
ops.pop();
}
while (!vals.empty()) {
vals.pop();
}
pos = 0;
int ans;
while (true) {
next_token(s);
if (token == 'd') {
vals.push(num);
} else if (token == '$') {
if (!vals.empty()) {
int a = vals.top();
vals.pop();
while (!ops.empty()) {
int b = vals.top();
vals.pop();
char ch = ops.top();
ops.pop();
if (ch == '+') {
a += b;
} else {
a = b - a;
}
}
ans = a;
}
break;
} else {
while (!ops.empty() && getpriority(ops.top()) >= getpriority(token)) {
char ch = ops.top();
if ((ch == '+' || ch == '-') && !vals.empty()) {
int a = vals.top();
vals.pop();
if (vals.empty()) {
vals.push(a);
break;
}
int b = vals.top();
vals.pop();
ops.pop();
if (ch == '+') {
vals.push(a + b);
} else {
vals.push(b - a);
}
} else {
break;
}
}
if (token == ')') {
ops.pop();
} else {
ops.push(token);
}
}
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: