[LC] 541. Reverse String II
2024-10-08 19:35:34
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:
- The string consists of lower English letters only.
- 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;
}
}
}
最新文章
- LABjs(类似于LazyLoad,但它更加方便管理依赖关系)
- URL编码表%20Base64编码表%20HTTP消息含义
- MySQL学习指引
- iOS视图生命周期与视图控制器关系
- Python之list添加新元素、删除元素、替换元素
- linux下的终端模拟器urxvt的配置
- java读取目录下所有csv文件数据,存入三维数组并返回
- 转载 asp.net的Request.ServerVariables参数说明
- 遇到autoreconf: not found
- android-----JNI学习 helloworld
- 【翻译自mos文章】rman 备份时报:ORA-02396: exceeded maximum idle time
- Horizon/DomainWorkFlow
- Twitter数据非API采集方法
- 深入理解 LINQ to SQL 生成的 SQL 语句
- 多线程之间的通信(等待唤醒机制、Lock 及其它线程的方法)
- 安装Logtail(Linux系统)
- Async:简洁优雅的异步之道
- 【Jmeter_WebService接口】对项目中的GetProduct接口生成性能脚本
- responsiveslides 插件(图片轮播插件)
- .net页面生命周期【转】
热门文章
- 高级变量类型(列表,元组,字典,字符串,公共方法,变量高级)for循环
- 吴裕雄--天生自然MySQL学习笔记:MySQL 查询数据
- 吴裕雄--天生自然 JAVASCRIPT开发学习:弹窗
- JDK的3个bug啊,你get到了吗?
- Python—程序设计:观察者模式
- shift+alt 可对notepadplusplus 打开的文档进行列操作
- 爬虫之xpath解析库
- Mybatis 使用分页查询亿级数据 性能问题 DB使用ORACLE
- PAT Advanced 1059 Prime Factors (25) [素数表的建⽴]
- shift+回车,换行。断点。