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)
相关推荐
黎宇幻生2 小时前
Java全栈学习笔记33
java·笔记·学习
朗迹 - 张伟3 小时前
Golang安装笔记
开发语言·笔记·golang
siy23336 小时前
[c语言日记] 数组的一种死法和两种用法
c语言·开发语言·笔记·学习·链表
不会聊天真君64712 小时前
ES(springcloud笔记第五期)
笔记·elasticsearch·spring cloud
汇能感知12 小时前
光谱相机在AI眼镜领域中的应用
经验分享·笔记·科技
汇能感知12 小时前
光谱相机的图像模式
经验分享·笔记·科技
XFF不秃头13 小时前
力扣刷题笔记-三数之和
c++·笔记·算法·leetcode
被遗忘的旋律.14 小时前
Linux驱动开发笔记(十)——中断
linux·驱动开发·笔记
nnerddboy14 小时前
Linux嵌入式自学笔记(基于野火EBF6ULL):1.配置环境
linux·笔记·单片机·嵌入式硬件
二进制怪兽16 小时前
[笔记] 系统分析师 第八章 软件工程
笔记