Skip to content

Commit d6531b0

Browse files
author
ironartisan
committed
添加0541翻转字符串java代码
1 parent 5b99941 commit d6531b0

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

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

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,35 @@ class Solution {
152152
}
153153
}
154154
```
155+
```java
156+
// 解法3
157+
class Solution {
158+
public String reverseStr(String s, int k) {
159+
char[] ch = s.toCharArray();
160+
// 1. 每隔 2k 个字符的前 k 个字符进行反转
161+
for (int i = 0; i< ch.length; i += 2 * k) {
162+
// 2. 剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符
163+
if (i + k <= ch.length) {
164+
reverse(ch, i, i + k -1);
165+
continue;
166+
}
167+
// 3. 剩余字符少于 k 个,则将剩余字符全部反转
168+
reverse(ch, i, ch.length - 1);
169+
}
170+
return new String(ch);
155171

172+
}
173+
// 定义翻转函数
174+
public void reverse(char[] ch, int i, int j) {
175+
for (; i < j; i++, j--) {
176+
char temp = ch[i];
177+
ch[i] = ch[j];
178+
ch[j] = temp;
179+
}
180+
181+
}
182+
}
183+
```
156184
Python:
157185
```python
158186
class Solution:

0 commit comments

Comments
 (0)