[抄题]:
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"
[暴力解法]:
时间分析:
空间分析:
[奇葩输出条件]:
[奇葩corner case]:
[思维问题]:
不知道怎么写复杂的swap:原来是用的封装
[一句话思路]:
特殊情况比较重要:每2k翻转一次,n<k时直接就翻转n了
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
/**
* 0 k 2k 3k
* |-----------|-----------|-----------|---
* +--reverse--+ +--reverse--+
*/
[一刷]:
- 第n位是n - 1,不是i + n - 1,怎么会出这种错呢
- swap中有while循环,要一直进行,最好写成l r,这都不会说明基础太差
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
不知道怎么写复杂的swap:原来是用的封装
[复杂度]:Time complexity: O(n) Space complexity: O(n)
[英文数据结构或算法,为什么不用别的数据结构或算法]:
[关键模板化代码]:
swap函数
public void swap(char[] words, int i, int j) { while (i < j) { char temp = words[i]; words[i] = words[j]; words[j] = temp; i++; j--; } }
[其他解法]:
[Follow Up]:
[LC给出的题目变变变]:
[代码风格] :
class Solution { public String reverseStr(String s, int k) { //corner case if (s == null) { return null; } if (k == 0) { return s; } //convert char[] words = s.toCharArray(); int i = 0; int n = s.length(); //while (i < n) while (i < n) { //define j int j = Math.min(i + k - 1, n - 1); swap(words, i, j); //i += 2k; i += 2 * k; } //return return new String(words); } public void swap(char[] words, int i, int j) { while (i < j) { char temp = words[i]; words[i] = words[j]; words[j] = temp; i++; j--; } } }