1. 题目描述
2. 解题思路
创建一个栈stk
用于存储每次计算后的合法得分,使用int 型变量res
存储最终得分,依次遍历每个操作符并根据题目描述执行相应指令。
3. 代码实现
class Solution {
public:
int calPoints(vector<string>& operations) {
stack<int> stk;
int res = 0;
for (auto& operation : operations) {
switch (operation[0]) {
case '+': {
int score1 = stk.top();
stk.pop();
int score2 = stk.top();
stk.push(score1);
stk.push(score1 + score2);
res += score1 + score2;
break;
}
case 'D': {
int score = stk.top();
stk.push(score * 2);
res += score * 2;
break;
}
case 'C': {
res -= stk.top();
stk.pop();
break;
}
default: {
stk.push(stoi(operation));
res += stoi(operation);
}
}
}
return res;
}
};
4. c++知识点
stoi
是 C++11 引入的一个标准库函数,用于将字符串转换为整数。它是 std::string
类的一部分,定义在头文件 <string>
中。stoi
函数有多个重载版本,支持从字符串中提取整数,并可以处理不同的数值基数。
函数原型
int stoi(const std::string& str, std::size_t* pos = 0, int base = 10);
参数说明
str
:要转换的字符串。pos
:指向std::size_t
对象的指针,函数会把第一个未转换字符的位置存储在其中。如果没有提供这个参数,函数会忽略它。base
:整数的基数,默认为10。可以是2到36之间的任何值。
返回值
返回字符串表示的整数值。如果转换失败(例如字符串不表示有效的整数),函数会抛出异常。
异常
std::invalid_argument
:如果字符串不包含可转换的整数。std::out_of_range
:如果转换得到的值超出了结果类型的范围。