From d6531b0f2b9699031087ad660ea6744e5c36508a Mon Sep 17 00:00:00 2001 From: ironartisan Date: Fri, 27 Aug 2021 21:25:07 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00541=E7=BF=BB=E8=BD=AC?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2java=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0541.反转字符串II.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0541.反转字符串II.md b/problems/0541.反转字符串II.md index 02713c65..914fba23 100644 --- a/problems/0541.反转字符串II.md +++ b/problems/0541.反转字符串II.md @@ -152,7 +152,35 @@ class Solution { } } ``` +```java +// 解法3 +class Solution { + public String reverseStr(String s, int k) { + char[] ch = s.toCharArray(); + // 1. 每隔 2k 个字符的前 k 个字符进行反转 + for (int i = 0; i< ch.length; i += 2 * k) { + // 2. 剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符 + if (i + k <= ch.length) { + reverse(ch, i, i + k -1); + continue; + } + // 3. 剩余字符少于 k 个,则将剩余字符全部反转 + reverse(ch, i, ch.length - 1); + } + return new String(ch); + } + // 定义翻转函数 + public void reverse(char[] ch, int i, int j) { + for (; i < j; i++, j--) { + char temp = ch[i]; + ch[i] = ch[j]; + ch[j] = temp; + } + + } +} +``` Python: ```python class Solution: