mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 02:53:31 +08:00
feat(0541): 增加另一种Java版本写法
This commit is contained in:
@ -103,6 +103,7 @@ public:
|
|||||||
|
|
||||||
Java:
|
Java:
|
||||||
```Java
|
```Java
|
||||||
|
//解法一
|
||||||
class Solution {
|
class Solution {
|
||||||
public String reverseStr(String s, int k) {
|
public String reverseStr(String s, int k) {
|
||||||
StringBuffer res = new StringBuffer();
|
StringBuffer res = new StringBuffer();
|
||||||
@ -128,6 +129,28 @@ class Solution {
|
|||||||
return res.toString();
|
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:
|
Python:
|
||||||
|
Reference in New Issue
Block a user