/**
* <p>给定一个字符串 <code>s</code> 和一个整数 <code>k</code>,从字符串开头算起,每计数至 <code>2k</code> 个字符,就反转这 <code>2k</code> 字符中的前 <code>k</code> 个字符。</p>
*
* <ul>
* <li>如果剩余字符少于 <code>k</code> 个,则将剩余字符全部反转。</li>
* <li>如果剩余字符小于 <code>2k</code> 但大于或等于 <code>k</code> 个,则反转前 <code>k</code> 个字符,其余字符保持原样。</li>
* </ul>
*
* <p> </p>
*
* <p><strong>示例 1:</strong></p>
*
* <pre>
* <strong>输入:</strong>s = "abcdefg", k = 2
* <strong>输出:</strong>"bacdfeg"
* </pre>
*
* <p><strong>示例 2:</strong></p>
*
* <pre>
* <strong>输入:</strong>s = "abcd", k = 2
* <strong>输出:</strong>"bacd"
* </pre>
*
* <p> </p>
*
* <p><strong>提示:</strong></p>
*
* <ul>
* <li><code>1 <= s.length <= 10<sup>4</sup></code></li>
* <li><code>s</code> 仅由小写英文组成</li>
* <li><code>1 <= k <= 10<sup>4</sup></code></li>
* </ul>
* <div><div>Related Topics</div><div><li>双指针</li><li>字符串</li></div></div><br><div><li> 336</li><li> 0</li></div>
*/
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public static String reverseStr(String s, int k) {
for (int i = 0; i < s.length(); i += (k * 2)) {
if (i + k < s.length()) {
s = reverse(s, i, i + k - 1);
} else {
s = reverse(s, i, s.length() - 1);
}
}
return s;
}
//注意 swap之后要重新生成字符串
static String reverse(String s, int start, int end) {
char[] nums = s.toCharArray();
char temp;
while (start < end) {
temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
return new String(nums);
}
}
//leetcode submit region end(Prohibit modification and deletion)