代码随想录算法训练营第八天|字符串part1

344.反转字符串

题目链接:344. 反转字符串 - 力扣(LeetCode)

文章讲解:代码随想录

 思路:简单题,交换标之和等于数组长度-1的元素

class Solution {
public:
    void reverseString(vector<char>& s) {
        int size=s.size();
        for(int i=0;i<size/2;i++){
            auto temp=s[i];
            s[i]=s[size-i-1];
            s[size-i-1]=temp;
        }
        
    }
};

541. 反转字符串II

题目链接:541. 反转字符串 II - 力扣(LeetCode)

文章讲解:代码随想录

class Solution {
public:
    string reverseStr(string s, int k) {
        bool index=true;
        int size=s.size();
        int n=size/k+1;
        if(size%k==0){
            n--;
        }
        //另一种优秀写法
        //int n = size / k + (size % k == 0 ? 0 : 1);  // 确保我们只处理有效的块

        for (int i = 0; i < n; i++) {
            int start = i * k;
            int end = min((i + 1) * k - 1, size - 1);  // end 确保不会越界

            if (index) {
                // 只反转每个块中的前 k 个字符
                for (int j = 0; j < (end - start + 1) / 2; j++) {
                    swap(s[start + j], s[end - j]);
                }
            }
            index = !index;  // 反转标志切换
        }

        return s;
    }
};

 这里end=min{}的思想真的不错!!!!

代码随想录解法:

class Solution {
public:
    string reverseStr(string s, int k) {
        for (int i = 0; i < s.size(); i += (2 * k)) {
            // 1. 每隔 2k 个字符的前 k 个字符进行反转
            // 2. 剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符
            if (i + k <= s.size()) {
                reverse(s.begin() + i, s.begin() + i + k );
            } else {
                // 3. 剩余字符少于 k 个,则将剩余字符全部反转。
                reverse(s.begin() + i, s.end());
            }
        }
        return s;
    }
};

卡码网:54.替换数字

题目链接:54. 替换数字(第八期模拟笔试)

文章讲解:

#include <iostream>
using namespace std;
int main() {
    string s;
    while (cin >> s) {
        int count=0;
        for(int i=0;i<s.size();i++){
            if(s[i]>='0'&&s[i]<='9'){     //这里与字符比较使用 ‘0’这个是字符 0是整数不能与字符比较
                count++;
            }
        }
        int sOldIndex = s.size() - 1;   
         s.resize(s.size() + count * 5);       //这里学习字符串扩充的写法
         int sNewIndex = s.size() - 1;
          while (sOldIndex >= 0) {
            if (s[sOldIndex] >= '0' && s[sOldIndex] <= '9') {
                s[sNewIndex--] = 'r';
                s[sNewIndex--] = 'e';
                s[sNewIndex--] = 'b';
                s[sNewIndex--] = 'm';
                s[sNewIndex--] = 'u';
                s[sNewIndex--] = 'n';
            } else {
                s[sNewIndex--] = s[sOldIndex];
            }
            sOldIndex--;
        }
        cout << s << endl;       
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值