541. Reverse String II (C++)

题目:

Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.
给定一个字符串和一个整数k,你需要反转从字符串开始计数的每2k个字符的前k个字符。 如果剩余少于k个字符,则将所有字符都反转。 如果小于2k但大于或等于k个字符,则反转前k个字符,并将另一个作为原始字符。

Example:

Input: s = “abcdefg”, k = 2
Output: “bacdfeg”
输入:s =“abcdefg”,k = 2
输出:“bacdfeg”
Restrictions:
The string consists of lower English letters only.
Length of the given string and k will in the range [1, 10000]
限制:
字符串只包含较低的英文字母。
给定字符串和k的长度将在范围[1,10000]

解答:

直接给出我的答案:9ms

class Solution {
public:
    string reverseStr(string s, int k) {
    string m = s;//创建一个一样的字符串,修改的时候直接m[a]=s[b];比较方便
    int a = 2 * k;//以2k为一个周期,改的时候改半个周期
    int d = s.length();//以后还会多次用到,最好先保存一下

    for (int i = 0; i < d; i++)
    {
        int b = i%a;
        int c = i - b;
        int e = 2 * c + k - 1 - i;//需要交换的元素
        if (b < k&&e<d)
        {
            m[i]= s[e];//不需要swap就可以“交换”元素值
        }
    }
    //只有上面的运算后答案有可能是不对的,比如
    //输入:12345678 3
    //输出:32145678,不符合题目要求应输出:32145687
    int f=d%a;//余数,注意是对2k的,其值可能大于k
    int g = d - f;
    if (f<k)
    {
        for (int j = 0; j < f; j++)
        {
            m[g + j] = s[g + f -1 - j];
        }
    }
    return m;
    }
};

总结:

是个简单题,但要求计算不能出错,细心度还是要有的,写的时候出了很多次错,以后要加油啊~~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值