英文原文
Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.
If there are fewer 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 1:
Input: s = "abcdefg", k = 2 Output: "bacdfeg"
Example 2:
Input: s = "abcd", k = 2 Output: "bacd"
Constraints:
1 <= s.length <= 104sconsists of only lowercase English letters.1 <= k <= 104
中文题目
给定一个字符串 s 和一个整数 k,从字符串开头算起,每计数至 2k 个字符,就反转这 2k 字符中的前 k 个字符。
- 如果剩余字符少于
k个,则将剩余字符全部反转。 - 如果剩余字符小于
2k但大于或等于k个,则反转前k个字符,其余字符保持原样。
示例 1:
输入:s = "abcdefg", k = 2 输出:"bacdfeg"
示例 2:
输入:s = "abcd", k = 2 输出:"bacd"
提示:
1 <= s.length <= 104s仅由小写英文组成1 <= k <= 104
通过代码
高赞题解
模拟
使用 l 和 r 两个指针分别圈出每次需要翻转的“理论”范围,每次翻转完更新 l 和 r,同时注意范围 $[l, r]$ 内不足 $k$ 个的情况(将 r 与真实边界 n - 1取个 $min$)。
代码:
[]class Solution { public String reverseStr(String s, int k) { char[] cs = s.toCharArray(); int n = s.length(); for (int l = 0; l < n; l = l + 2 * k) { int r = l + k - 1; reverse(cs, l, Math.min(r, n - 1)); } return String.valueOf(cs); } void reverse(char[] cs, int l, int r) { while (l < r) { char c = cs[l]; cs[l] = cs[r]; cs[r] = c; l++; r--; } } }
- 时间复杂度:$O(n)$
- 空间复杂度:Java 中
String属于不可变,复杂度为 $O(n)$
特别感谢
再次感谢昨天有给三叶点 ❤️ 的小伙伴,截止至 2021/08/20 10:00:00 有 $115$ 人,太有排面了,截个全家福纪念一下 🤣 呜呜呜,感谢(其他没有入镜的同学,是在帮忙拿相机拍照啦,也感谢他们 ~

最后
如果有帮助到你,请给题解点个赞和收藏,让更多的人看到 ~ (“▔□▔)/
也欢迎你 关注我(公主号后台回复「送书」即可参与长期看题解学算法送实体书活动)或 加入「组队打卡」小群 ,提供写「证明」&「思路」的高质量题解。
所有题解已经加入 刷题指南,欢迎 star 哦 ~
统计信息
| 通过次数 | 提交次数 | AC比率 |
|---|---|---|
| 79392 | 131360 | 60.4% |
提交历史
| 提交时间 | 提交结果 | 执行时间 | 内存消耗 | 语言 |
|---|
相似题目
| 题目 | 难度 |
|---|---|
| 反转字符串 | 简单 |
| 反转字符串中的单词 III | 简单 |