卡码网54(代码随想录:替换数字)
C++:
注意:
这道题的关键是填充number的方法,如果从前向后填充,那么每次都需要将字符串后面的元素整体向后移动(时间复杂度O(n^2)),而如果从前向后填充则不需要。
//卡码网54题:替换数字
#include <iostream>
#include <string>using namespace std;int main(void)
{string s;int count = 0;while(cin >> s){int oldsize = s.size();for(int i=0; i < s.size(); i++){if(s[i] >= '0' && s[i] <= '9')count++;}//扩充字符串大小s.resize(oldsize + 5*count);//从后向前填充数组int j = s.size() - 1;for(int i = oldsize-1; i >= 0; i--){if(s[i] >= '0' && s[i] <= '9'){s[j] = 'r';s[j-1] = 'e';s[j-2] = 'b';s[j-3] = 'm';s[j-4] = 'u';s[j-5] = 'n';j -= 6;}else{s[j] = s[i];j--;}}cout << s << endl;cout << s.size() << endl;}
}
Python:
class Solution:def replace_number(self, s:str)->str:res = list(s)for i in range(len(s)):if res[i] in ['1','2','3','4','5','6','7','8','9']:res[i] = 'number'return ''.join(res)sol = Solution()
s = input()
result = sol.replace_number(s)
print(result)