参考链接
- https://leetcode-cn.com/problems/replace-all-digits-with-characters/
题目描述
给你一个下标从 0 开始的字符串 s ,它的偶数下标处为小写英文字母,奇数下标处为数字。
定义一个函数 shift(c, x) ,其中 c 是一个字符且 x 是一个数字,函数返回字母表中 c 后面第 x 个字符。
比方说,shift(‘a’, 5) = ‘f’ 和 shift(‘x’, 0) = ‘x’ 。
对于每个奇数下标 i ,你需要将数字 s[i] 用 shift(s[i-1], s[i]) 替换。
请你替换所有数字以后,将字符串 s 返回。题目保证 shift(s[i-1], s[i]) 不会超过 ‘z’ 。
解题思路
直接遍历奇数索引,把前一位字符加上偏移量即可。偏移量就是数字字符与字符‘0’的距离。
代码
class Solution {
public:
string replaceDigits(string s) {
for (int i = 0; 2 * i + 1 < s.size(); i ++)
{
s[2 * i + 1] = s[2 * i] + s[2 * i + 1] - '0';
}
return s;
}
};