From b24e3f04ac05798947ac1bd580c7a094c3353e19 Mon Sep 17 00:00:00 2001 From: Flow-sandyu <72751523+Flow-sandyu@users.noreply.github.com> Date: Mon, 3 Oct 2022 19:37:53 +0800 Subject: [PATCH] =?UTF-8?q?update=EF=BC=9A=E5=89=91=E6=8C=87Offer58-II.?= =?UTF-8?q?=E5=B7=A6=E6=97=8B=E8=BD=AC=E5=AD=97=E7=AC=A6=E4=B8=B2.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 解法二:空间复杂度:O(1)。用原始数组来进行反转操作 思路:先整个字符串反转,再反转前面的,最后反转后面 n 个 --- .../剑指Offer58-II.左旋转字符串.md | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/problems/剑指Offer58-II.左旋转字符串.md b/problems/剑指Offer58-II.左旋转字符串.md index bf5d3f90..b14c26cc 100644 --- a/problems/剑指Offer58-II.左旋转字符串.md +++ b/problems/剑指Offer58-II.左旋转字符串.md @@ -115,6 +115,29 @@ class Solution { } ``` +```java +//解法二:空间复杂度:O(1)。用原始数组来进行反转操作 +//思路为:先整个字符串反转,再反转前面的,最后反转后面 n 个 +class Solution { + public String reverseLeftWords(String s, int n) { + char[] chars = s.toCharArray(); + reverse(chars, 0, chars.length - 1); + reverse(chars, 0, chars.length - 1 - n); + reverse(chars, chars.length - n, chars.length - 1); + return new String(chars); + } + + public void reverse(char[] chars, int left, int right) { + while (left < right) { + chars[left] ^= chars[right]; + chars[right] ^= chars[left]; + chars[left] ^= chars[right]; + left++; + right--; + } + } +``` + python: ```python