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: