File tree Expand file tree Collapse file tree 1 file changed +23
-0
lines changed Expand file tree Collapse file tree 1 file changed +23
-0
lines changed Original file line number Diff line number Diff line change @@ -103,6 +103,7 @@ public:
103
103
104
104
Java:
105
105
``` Java
106
+ // 解法一
106
107
class Solution {
107
108
public String reverseStr (String s , int k ) {
108
109
StringBuffer res = new StringBuffer ();
@@ -128,6 +129,28 @@ class Solution {
128
129
return res. toString();
129
130
}
130
131
}
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
+ }
131
154
```
132
155
133
156
Python:
You can’t perform that action at this time.
0 commit comments