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]
class Solution {
public String reverseStr(String s, int k) {
int i = 0;
char[] charArr = s.toCharArray();
while (i < charArr.length) {
int j = Math.min(i + k - 1, charArr.length - 1);
swap(i, j, charArr);
i += 2 * k;
}
return new String(charArr);
} private void swap(int i, int j, char[] charArr) {
while (i < j) {
char temp = charArr[i];
charArr[i] = charArr[j];
charArr[j] = temp;
i += 1;
j -= 1;
}
}
}

最新文章

  1. LABjs(类似于LazyLoad,但它更加方便管理依赖关系)
  2. URL编码表%20Base64编码表%20HTTP消息含义
  3. MySQL学习指引
  4. iOS视图生命周期与视图控制器关系
  5. Python之list添加新元素、删除元素、替换元素
  6. linux下的终端模拟器urxvt的配置
  7. java读取目录下所有csv文件数据,存入三维数组并返回
  8. 转载 asp.net的Request.ServerVariables参数说明
  9. 遇到autoreconf: not found
  10. android-----JNI学习 helloworld
  11. 【翻译自mos文章】rman 备份时报:ORA-02396: exceeded maximum idle time
  12. Horizon/DomainWorkFlow
  13. Twitter数据非API采集方法
  14. 深入理解 LINQ to SQL 生成的 SQL 语句
  15. 多线程之间的通信(等待唤醒机制、Lock 及其它线程的方法)
  16. 安装Logtail(Linux系统)
  17. Async:简洁优雅的异步之道
  18. 【Jmeter_WebService接口】对项目中的GetProduct接口生成性能脚本
  19. responsiveslides 插件(图片轮播插件)
  20. .net页面生命周期【转】

热门文章

  1. 高级变量类型(列表,元组,字典,字符串,公共方法,变量高级)for循环
  2. 吴裕雄--天生自然MySQL学习笔记:MySQL 查询数据
  3. 吴裕雄--天生自然 JAVASCRIPT开发学习:弹窗
  4. JDK的3个bug啊,你get到了吗?
  5. Python—程序设计:观察者模式
  6. shift+alt 可对notepadplusplus 打开的文档进行列操作
  7. 爬虫之xpath解析库
  8. Mybatis 使用分页查询亿级数据 性能问题 DB使用ORACLE
  9. PAT Advanced 1059 Prime Factors (25) [素数表的建⽴]
  10. shift+回车,换行。断点。