541:反转字符串 II

This commit is contained in:
huangge1199 2021-08-12 11:38:02 +08:00
parent 8262a1e4d0
commit 3651d52d2e
2 changed files with 96 additions and 0 deletions

View File

@ -0,0 +1,63 @@
//给定一个字符串 s 和一个整数 k从字符串开头算起 2k 个字符反转前 k 个字符
//
//
// 如果剩余字符少于 k 则将剩余字符全部反转
// 如果剩余字符小于 2k 但大于或等于 k 则反转前 k 个字符其余字符保持原样
//
//
//
//
// 示例 1
//
//
//输入s = "abcdefg", k = 2
//输出"bacdfeg"
//
//
// 示例 2
//
//
//输入s = "abcd", k = 2
//输出"bacd"
//
//
//
//
// 提示
//
//
// 1 <= s.length <= 104
// s 仅由小写英文组成
// 1 <= k <= 104
//
// Related Topics 双指针 字符串
// 👍 139 👎 0
package leetcode.editor.cn;
//541:反转字符串 II
class ReverseStringIi {
public static void main(String[] args) {
//测试代码
Solution solution = new ReverseStringIi().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public String reverseStr(String s, int k) {
char[] a = s.toCharArray();
for (int start = 0; start < a.length; start += 2 * k) {
int i = start, j = Math.min(start + k - 1, a.length - 1);
while (i < j) {
char tmp = a[i];
a[i++] = a[j];
a[j--] = tmp;
}
}
return new String(a);
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,33 @@
<p>给定一个字符串 <code>s</code> 和一个整数 <code>k</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>&nbsp;</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>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>
<li><code>s</code> 仅由小写英文组成</li>
<li><code>1 &lt;= k &lt;= 10<sup>4</sup></code></li>
</ul>
<div><div>Related Topics</div><div><li>双指针</li><li>字符串</li></div></div>\n<div><li>👍 139</li><li>👎 0</li></div>