代码随想录第八天: 344.反转字符串、541. 反转字符串II、卡码网:54.替换数字

344.反转字符串,利用双指针交换字符串左右位置的字符,没什么好说的

#include <iostream>
#include <vector>

void reverseString(std::vector<char> &s)
{
    int left = 0;
    int right = s.size() - 1;
    while (left < right)
    {
        // 交换左右指针所指向的元素
        char temp = s[left];
        s[left] = s[right];
        s[right] = temp;
        // 向中心移动指针
        left++;
        right--;
    }
}

int main()
{
    std::vector<char> s = {'h', 'e', 'l', 'l', 'o'};
    reverseString(s);
    for (char c : s)
    {
        std::cout << c;
    }
    std::cout << std::endl;
    return 0;
}

541. 反转字符串II,固定段数反转字符串,可以在写循环边界的时候注意一下,反转实现用reverse,代码如下:

#include <iostream>
#include <algorithm> // 包含 std::reverse
#include <string>

void reverseStr(std::string &s, int k)
{
    int n = s.length();
    for (int start = 0; start < n; start += 2 * k)
    {
        // 反转从 start 开始的前 k 个字符
        // 如果剩余字符少于 k 个,反转所有剩余字符
        if (start + k <= n)
        {
            std::reverse(s.begin() + start, s.begin() + start + k);
        }
        else
        {
            std::reverse(s.begin() + start, s.end());
        }
    }
}

int main()
{
    std::string s = "abcdefg";
    int k = 2;
    reverseStr(s, k);
    std::cout << s << std::endl; // 输出结果应为 "bacdfeg"
    return 0;
}

卡码网:54.替换数字,直接实现功能,懒得优化

#include <iostream>
#include <string>
#include <cctype> // 包含函数 isdigit

std::string replaceDigitsWithWord(const std::string &s)
{
    std::string result;
    for (char c : s)
    {
        if (isdigit(c))
        {
            result += "number";
        }
        else
        {
            result += c;
        }
    }
    return result;
}

int main()
{
    std::string s = "a1b2c3";
    std::string transformed = replaceDigitsWithWord(s);
    std::cout << transformed << std::endl; // 输出 "anumberbnumbercnumber"
    return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值