20240308-Day 26-点亮代码技能

卡码网54(代码随想录:替换数字)

C++:

注意:

这道题的关键是填充number的方法,如果从前向后填充,那么每次都需要将字符串后面的元素整体向后移动(时间复杂度O(n^2)),而如果从前向后填充则不需要。

cpp 复制代码
//卡码网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:

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)
相关推荐
ReedFoley10 小时前
【笔记】动手学Ollama 第五章 Ollama 在 LangChain 中的使用 - Python 集成
笔记·langchain
Mr Sorry16 小时前
Non-stationary Diffusion For Probabilistic Time Series Forecasting论文阅读笔记
论文阅读·笔记
南猿北者17 小时前
Cmake学习笔记
笔记·学习·策略模式
码小文17 小时前
Altium Designer 22使用笔记(8)---PCB电气约束设置
笔记·嵌入式硬件·硬件工程·ad22
UserNamezhangxi20 小时前
kotlin 协程笔记
java·笔记·kotlin·协程
翻滚的小@强1 天前
数据挖掘笔记:点到线段的距离计算
人工智能·笔记·数据挖掘
会思考的猴子1 天前
UE5 PCG 笔记(二) Difference 节点
笔记·ue5
yuxb731 天前
Linux 文本处理与 Shell 编程笔记:正则表达式、sed、awk 与变量脚本
linux·笔记·正则表达式
饕餮争锋1 天前
设计模式笔记_行为型_访问者模式
笔记·设计模式·访问者模式
不羁。。1 天前
【撸靶笔记】第七关:GET - Dump into outfile - String
数据库·笔记·oracle