題目鏈接:https://leetcode-cn.com/problems/baseball-game/description/
emmmm,一道水題,然而菜雞的我當時自己都寫不出來,這道題用到的棧的思想,這裏用一個動態數組來模擬棧,當是數字時,直接將數字入棧,當是‘+’時將st.back()和st[st.size()-2]求和入棧,當是‘D’時,將st.back()*2入棧,當是‘C’時,棧頂元素出棧,最後求和就是結果。
class Solution {
public:
int calPoints(vector<string>& ops) {
vector<int> st;
for(int i = 0;i<ops.size();i++){
if(ops[i]=="C"){
st.pop_back();
}
else if(ops[i]=="D"){
st.push_back(2*st.back());
}
else if(ops[i]=="+"){
st.push_back(st.back()+st[st.size()-2]);
}else {
st.push_back(stoi(ops[i]));
}
}
return accumulate(st.begin(), st.end(), 0);
}
};