这个题目除了分类讨论就没什么了
LeetCode链接:541. 反转字符串 II
1.题目描述
给定一个字符串 s
和一个整数 k
,从字符串开头算起,每计数至 2k
个字符,就反转这 2k
字符中的前 k
个字符。
- 如果剩余字符少于
k
个,则将剩余字符全部反转。
- 如果剩余字符小于
2k
但大于或等于 k
个,则反转前 k
个字符,其余字符保持原样。
示例 1:
1 2
| 输入:s = "abcdefg", k = 2 输出:"bacdfeg"
|
示例 2:
1 2
| 输入:s = "abcd", k = 2 输出:"bacd"
|
提示:
- $1 <= s.length <= 10^4$
s
仅由小写英文组成
- $1 <= k <= 10^4$
2.题解
2.1 直接法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| class Solution { public String reverseStr(String s, int k) { char[] chs = s.toCharArray(); int count = chs.length / (2 * k); for (int i = 0; i < count; i++) { reverseStr(chs, 2 * i * k, 2 * i * k + k - 1); }
int mod = chs.length % (2 * k); if (mod >= k) { reverseStr(chs, 2 * count * k, 2 * count * k + k - 1); } else { reverseStr(chs, 2 * count * k, chs.length - 1); }
return new String(chs); }
public void reverseStr(char[] chs, int begin, int end) { while (begin < end) { char c = chs[end]; chs[end--] = chs[begin]; chs[begin++] = c; } } }
|
2.2 双指针
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| class Solution { public String reverseStr(String s, int k) { char[] chs = s.toCharArray(); int begin = 0, end;
while (begin < chs.length) { int reaminLen = chs.length - begin; end = reaminLen >= k ? begin + k - 1 : chs.length - 1; reverseStr(chs, begin, end); begin += 2 * k; }
return new String(chs); }
public void reverseStr(char[] chs, int begin, int end) { while (begin < end) { char c = chs[end]; chs[end--] = chs[begin]; chs[begin++] = c; } } }
|