添加0541.反转字符串II Java版本

添加0541.反转字符串II Java版本
This commit is contained in:
Powerstot
2021-05-12 20:55:21 +08:00
committed by GitHub
parent 5307170c8d
commit df60da0306

View File

@ -101,7 +101,36 @@ public:
Java
```Java
class Solution {
public String reverseStr(String s, int k) {
StringBuffer res = new StringBuffer();
for (int i = 0; i < s.length(); i += (2 * k)) {
StringBuffer temp = new StringBuffer();
// 剩余字符大于 k 个,每隔 2k 个字符的前 k 个字符进行反转
if (i + k <= s.length()) {
// 反转前 k 个字符
temp.append(s.substring(i, i + k));
res.append(temp.reverse());
// 反转完前 k 个字符之后,如果紧接着还有 k 个字符,则直接加入这 k 个字符
if (i + 2 * k <= s.length()) {
res.append(s.substring(i + k, i + 2 * k));
// 不足 k 个字符,则直接加入剩下所有字符
} else {
res.append(s.substring(i + k, s.length()));
}
continue;
}
// 剩余字符少于 k 个,则将剩余字符全部反转。
temp.append(s.substring(i, s.length()));
res.append(temp.reverse());
}
return res.toString();
}
}
```
Python