Skip to content

Commit 69ab3b8

Browse files
Merge pull request #415 from KailokFung/master
feat(0541): 增加另一种Java版本写法
2 parents b765af9 + 78b32e8 commit 69ab3b8

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

problems/0541.反转字符串II.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ public:
103103

104104
Java:
105105
```Java
106+
//解法一
106107
class Solution {
107108
public String reverseStr(String s, int k) {
108109
StringBuffer res = new StringBuffer();
@@ -128,6 +129,28 @@ class Solution {
128129
return res.toString();
129130
}
130131
}
132+
133+
//解法二(似乎更容易理解点)
134+
//题目的意思其实概括为 每隔2k个反转前k个,尾数不够k个时候全部反转
135+
class Solution {
136+
public String reverseStr(String s, int k) {
137+
char[] ch = s.toCharArray();
138+
for(int i = 0; i < ch.length; i += 2 * k){
139+
int start = i;
140+
//这里是判断尾数够不够k个来取决end指针的位置
141+
int end = Math.min(ch.length - 1, start + k - 1);
142+
//用异或运算反转
143+
while(start < end){
144+
ch[start] ^= ch[end];
145+
ch[end] ^= ch[start];
146+
ch[start] ^= ch[end];
147+
start++;
148+
end--;
149+
}
150+
}
151+
return new String(ch);
152+
}
153+
}
131154
```
132155

133156
Python:

0 commit comments

Comments
 (0)