From 78b32e8c6c2c7708e1407c729ceebfeeca033f4d Mon Sep 17 00:00:00 2001 From: KailokFung Date: Thu, 17 Jun 2021 17:53:56 +0800 Subject: [PATCH] =?UTF-8?q?feat(0541):=20=E5=A2=9E=E5=8A=A0=E5=8F=A6?= =?UTF-8?q?=E4=B8=80=E7=A7=8DJava=E7=89=88=E6=9C=AC=E5=86=99=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0541.反转字符串II.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/problems/0541.反转字符串II.md b/problems/0541.反转字符串II.md index 00581fc0..4b3ed43b 100644 --- a/problems/0541.反转字符串II.md +++ b/problems/0541.反转字符串II.md @@ -103,6 +103,7 @@ public: Java: ```Java +//解法一 class Solution { public String reverseStr(String s, int k) { StringBuffer res = new StringBuffer(); @@ -128,6 +129,28 @@ class Solution { return res.toString(); } } + +//解法二(似乎更容易理解点) +//题目的意思其实概括为 每隔2k个反转前k个,尾数不够k个时候全部反转 +class Solution { + public String reverseStr(String s, int k) { + char[] ch = s.toCharArray(); + for(int i = 0; i < ch.length; i += 2 * k){ + int start = i; + //这里是判断尾数够不够k个来取决end指针的位置 + int end = Math.min(ch.length - 1, start + k - 1); + //用异或运算反转 + while(start < end){ + ch[start] ^= ch[end]; + ch[end] ^= ch[start]; + ch[start] ^= ch[end]; + start++; + end--; + } + } + return new String(ch); + } +} ``` Python: