首页 > 试题广场 >

替换字符串中的数字成"num"

[编程题]替换字符串中的数字成"num&qu
  • 热度指数:583 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解

替换字符串中的数字成"num",如果数字相连,则相连数字一起替换成"num"。

数字指0123456789

如:"abvhjb123ddd" 替换成 "abvhjbnumddd"

如:"abvhjb1y3ddd" 替换成 "abvhjbnumynumddd"

示例1

输入

"abvhjb123ddd"

输出

"abvhjbnumddd"
正则表达式快速解法
class Solution:
    def replaceStr(self , s):
        # write code here
        import re
        return re.sub("\d+", "num", s)
object Solution {
    /**
    * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
    *
    * 
        * @param s string字符串 
        * @return string字符串
    */
    def replaceStr(s: String): String = {
        // write code here
        s.replaceAll("[0-9]+", "num")
    }
}
中规中矩遍历替换也行
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return string字符串
     */
    public String replaceStr (String s) {
        // write code here
        StringBuilder sb = new StringBuilder();
        boolean prevExistNum = false;     // 标记前面是否是数字
        for(int i = 0; i < s.length(); i++){
            char c = s.charAt(i);
            if(c >= '0' && c <= '9'){
                prevExistNum = true;
            }else{
                if(prevExistNum){
                    sb.append("num");
                    prevExistNum = false;
                }
                sb.append(c);
            }
        }
        if(prevExistNum) sb.append("num");    // 防止字符串以数字结尾
        return sb.toString();
    }
}

编辑于 2021-09-22 11:56:10 回复(0)
string replaceStr(string s) {
    // write code here
    string res = s;
    for(int i = 0 ; i < res.size(); i++){
        if(res[i] >= '0' && res[i] <= '9'){
            int j = i;
            while(j <= res.size() && (res[j] >= '0' && res[j] <= '9')){
                j++;
            }
            res.replace(i,j-i,"num");
        }
    }
    return res;
}

发表于 2021-09-16 16:52:32 回复(0)
# 字符串累加,无数字则加当前字符串,单个数字则加一个num,主要是多个连续数字
classSolution:
    defreplaceStr(self, s):
        index =0
        res =""
        whileindex < len(s):
            temp_index =1
            number_list =[str(i) fori inrange(9)]
            whiletemp_index +index < len(s) ands[index] innumber_list ands[index +temp_index] innumber_list:
                temp_index +=1
            iftemp_index > 1ors[index] innumber_list:
                res +="num"
                index +=temp_index
                continue
            res +=s[index]
            index +=1
        returnres
发表于 2021-09-10 10:23:26 回复(0)