使用辅助空间
创建一个字符串,如果当前下标指向元素是字符就添加到该字符串后面,如果是数字,就添加number字符串到后面,最后返回结果。
1 2 3 4 5 6 7 8 9 10 11
| std::string replaceDigitsWithNumber(const std::string& s) { std::string result; for (char c : s) { if (std::isdigit(c)) { result.append("number"); } else { result.push_back(c); } } return result; }
|
不使用辅助空间
遍历字符串中数字个数 num,然后在原基础上 resize 扩容到 num * 6
空间大小。
从后往前遍历进行替换,让数据更少移动。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| void fillStr(std::string& str,int end) { str[end--] = 'r'; str[end--] = 'e'; str[end--] = 'b'; str[end--] = 'm'; str[end--] = 'u'; str[end] = 'n'; }
void replaceNumbers(std::string& str) { int numbers = 0; for (auto c : str) { if (isdigit(c)) { numbers++; } } int len = str.size() - 1; int expand_size = str.size() - numbers + numbers * 6; str.resize(expand_size); expand_size--; for (int i = len; i >= 0; i--) { if (isdigit(str[i])) { fillStr(str, expand_size); expand_size -= 6; } else { str[expand_size--] = str[i]; } } }
|