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)
相关推荐
yoothey1 小时前
异常学习笔记:为什么自定义异常后还要 throw?
笔记·学习
sulikey1 小时前
数据库系统概论4 - 更新与视图 期末速成课笔记
数据库·笔记·考试·期末速成·数据库系统概论
لا معنى له2 小时前
NeoVerse: Enhancing 4D World Model with in-the-wild Monocular Videos
人工智能·笔记·机器学习·语言模型
黄毛火烧雪下2 小时前
Java 基础笔记:文件、递归与字符编码
java·开发语言·笔记
学计算机的计算基2 小时前
链表算法上篇:LeetCode 206/234/141/142/160/21 题解与易错点
java·笔记·算法·链表
二哈赛车手3 小时前
新人笔记---idea索引失效问题解决方案
java·笔记·spring·elasticsearch·intellij-idea
A.零点3 小时前
【2个月 C 语言从入门到精通:零基础系统教程】第十二讲:深入了解指针(五)
c语言·开发语言·网络·笔记·visual studio
ctrl_v助手4 小时前
VisionPro (R) QuickBuild相机的连接
服务器·笔记·数码相机·c#
代码搬运媛4 小时前
Express 入门到精通笔记
笔记·express