mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 20:40:39 +08:00
添加0541翻转字符串java代码
This commit is contained in:
@ -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:
|
||||
|
Reference in New Issue
Block a user