mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
反转字符串Java其他解法
This commit is contained in:
@ -151,6 +151,23 @@ class Solution {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 第二种方法用temp来交换数值更多人容易理解些
|
||||
class Solution {
|
||||
public void reverseString(char[] s) {
|
||||
int l = 0;
|
||||
int r = s.length - 1;
|
||||
while(l < r){
|
||||
char temp = s[l];
|
||||
s[l] = s[r];
|
||||
s[r] = temp;
|
||||
l++;
|
||||
r--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
```
|
||||
|
||||
Python:
|
||||
@ -335,3 +352,4 @@ object Solution {
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
</a>
|
||||
|
||||
|
@ -194,6 +194,29 @@ class Solution {
|
||||
return new String(ch);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 解法二还可以用temp来交换数值,会的人更多些
|
||||
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){
|
||||
|
||||
char temp = ch[start];
|
||||
ch[start] = ch[end];
|
||||
ch[end] = temp;
|
||||
|
||||
start++;
|
||||
end--;
|
||||
}
|
||||
}
|
||||
return new String(ch);
|
||||
}
|
||||
}
|
||||
```
|
||||
```java
|
||||
// 解法3
|
||||
@ -469,3 +492,4 @@ impl Solution {
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
</a>
|
||||
|
||||
|
Reference in New Issue
Block a user