682. 棒球比赛
解法一:c++栈
class Solution {
public:
int calPoints(vector<string>& ops) {
stack<int> s;
int sum = 0;
for (int i = 0; i < ops.size(); i++) {//遍历ops,对每种情况处理
if (ops[i] == "C") {
s.pop();
}
else if (ops[i] == "D") {
int tmp = s.top() * 2;
s.push(tmp);
}
else if (ops[i] == "+") {
int tmp1 = s.top();
s.pop();
int tmp2 = s.top() + tmp1;
s.push(tmp1);
s.push(tmp2);
}
else { // 若是数字
int tmp = stoi(ops[i]);
s.push(tmp);
}
}
while(!s.empty()) { //求和
sum += s.top();
s.pop();
}
return sum;
}
};解法二:py栈
最后更新于