华为机试HJ96题解 | #表示数字#

表示数字

https://www.nowcoder.com/practice/637062df51674de8ba464e792d1a0ac6

#include <cctype>
#include <iostream>
//#include <string>
#include <bits/stdc++.h>
using namespace std;

// 双指针解法
string AddStartsBeforeAndAfterDigital(const std::string &s)
{
    string res;
    // 遍历字符串
    for (int i = 0; i < s.size(); ) {
        int j = i;
        // 当前字符是数字
        if (isdigit(s[j])) {
            // 找到最后一个数字(连续数字)
            while (isdigit(s[j]) && j < s.size()) {
                j++;
            }
            // 在连续数字前后加上*
            res += "*" + s.substr(i, j - i) + "*";
            // 记录最后一个数字的下一个字符
            i = j;
        } else {
            // 如果当前字符不是数字,则直接加上
            res += s[j];
            i++;
        }
    }

    return res;
}

int main() {
    string s;
    while (cin >> s) { // 注意 while 处理多个 case
        cout << AddStartsBeforeAndAfterDigital(s) << endl;
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 17:10
点赞 评论 收藏
分享
05-27 14:57
西北大学 golang
强大的社畜在走神:27届真不用急,可以搞点项目、竞赛再沉淀沉淀,我大二的时候还在天天打游戏呢
投递华为等公司10个岗位
点赞 评论 收藏
分享
05-26 22:25
门头沟学院 Java
Java小肖:不会是想叫你过去把你打一顿吧,哈哈哈
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务