leetcode-翻轉字符串-541

/** * <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>&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><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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章