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.

Example:

Input: s = "abcdefg", k = 2
Output: "bacdfeg"

Restrictions:

  1. The string consists of lower English letters only.
  2. Length of the given string and k will in the range [1, 10000]

这道题是之前那道题Reverse String的拓展,同样是翻转字符串,但是这里是每隔k隔字符,翻转k个字符,最后如果不够k个了的话,剩几个就翻转几个。比较直接的方法就是先用n/k算出来原字符串s能分成几个长度为k的字符串,然后开始遍历这些字符串,遇到2的倍数就翻转,翻转的时候注意考虑下是否已经到s末尾了,参见代码如下:

解法一:

class Solution {
public:
string reverseStr(string s, int k) {
int n = s.size(), cnt = n / k;
for (int i = ; i <= cnt; ++i) {
if (i % == ) {
if (i * k + k < n) {
reverse(s.begin() + i * k, s.begin() + i * k + k);
} else {
reverse(s.begin() + i * k, s.end());
}
}
}
return s;
}
};

在论坛里又发现了写法更为简洁的方法,就是每2k个字符来遍历原字符串s,然后进行翻转,翻转的结尾位置是取i+k和末尾位置之间的较小值,感觉很叼,参见代码如下:

解法二:

class Solution {
public:
string reverseStr(string s, int k) {
for (int i = ; i < s.size(); i += * k) {
reverse(s.begin() + i, min(s.begin() + i + k, s.end()));
}
return s;
}
};

类似题目:

Reverse String

参考资料:

https://discuss.leetcode.com/topic/82652/one-line-c/2

https://discuss.leetcode.com/topic/82626/java-concise-solution

LeetCode All in One 题目讲解汇总(持续更新中...)

最新文章

  1. js的单引号,双引号,转移符
  2. 2014-10-2 bug更新5 ecshop和ectouch解决动态ip登录超时和购物车清空问题
  3. PHP-Java-Bridge的使用(平安银行支付功能专版)
  4. jQuery+AJAX实现网页无刷新上传
  5. Retrofit 2.0 throwing @Field parameters can only be used with form encoding
  6. Bzoj 2705: [SDOI2012]Longge的问题 欧拉函数,数论
  7. 基于visual Studio2013解决面试题之0804复杂链表
  8. Java IO学习笔记四
  9. Hadoop 伪分布式安装、运行测试例子
  10. 约瑟夫环问题 --链表 C语言
  11. 【API知识】RestTemplate的使用
  12. Python3之弹性力学——应力张量2
  13. web调用本地exe应用程序并传入参数
  14. redis复习
  15. Inernet TLS协议注册表 开启
  16. 使用cmd命令进行导入
  17. python自动化之爬虫原理及简单案例
  18. Apache 配置多个HTTPS站点
  19. 什么是DSCP,如何使用DSCP标记搭配ROS策略
  20. 如何使用eslint

热门文章

  1. [poj1185]炮兵阵地_状压dp
  2. Jmeter中正则表达式提取器使用详解
  3. ASP.NET Core MVC 2.1 顶级参数验证
  4. Java面试总结(二)
  5. React Native 轻松集成统计功能(Android 篇)
  6. 如何查看与更改python的工作目录?
  7. 成功案例分享:raid5两块硬盘掉线数据丢失恢复方法
  8. 接触JS的变量
  9. python之路--day13---函数--三元表达式,递归,匿名函数,内置函数-----练习
  10. .Net Core MongoDB 简单操作。