传送门
水题,一眼栈
class Solution {
public:
int calPoints(vector<string>& ops) {
stack<int> stk;
for (auto el : ops) {
if (el[0] == 'C') {
if (!stk.empty()) {
stk.pop();
}
} else if (el[0] == 'D') {
int score = stk.top();
stk.push(score * 2);
} else if (el[0] == '+') {
int score1 = stk.top();stk.pop();
int score2 = stk.top();stk.pop();
int newScore = score1 + score2;
stk.push(score2);
stk.push(score1);
stk.push(newScore);
// cout << score1 << "+" << score2 << endl;
// cout << newScore << endl;
} else {
// string转int
int score = atoi(el.c_str());
// cout << score << endl;
stk.push(score);
}
}
int ans = 0;
while(!stk.empty()) {
ans += stk.top();
// cout << stk.top() << endl;
stk.pop();
}
return ans;
}
};
评论
评论功能已经关闭!