更新0541.反转字符串II Java版本

This commit is contained in:
zqh1059405318
2021-05-27 23:44:00 +08:00
parent fa25fab461
commit 7f3b661add

View File

@ -106,27 +106,24 @@ 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();
int length = s.length();
for (int i = 0; i < s.length(); i += (2 * k)) { int start = 0;
while (start < length) {
// 找到k处和2k处
StringBuffer temp = new StringBuffer(); StringBuffer temp = new StringBuffer();
// 剩余字符大于 k 个,每隔 2k 个字符的前 k 个字符进行反转 // 与length进行判断如果大于length了那就将其置为length
if (i + k <= s.length()) { int firstK = (start + k > length) ? length : start + k;
// 反转前 k 个字符 int secondK = (start + (2 * k) > length) ? length : start + (2 * k);
temp.append(s.substring(i, i + k));
res.append(temp.reverse());
// 反转完前 k 个字符之后,如果紧接着还有 k 个字符,则直接加入这 k 个字符 //无论start所处位置至少会反转一次
if (i + 2 * k <= s.length()) { temp.append(s.substring(start, firstK));
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()); res.append(temp.reverse());
// 如果firstK到secondK之间有元素这些元素直接放入res里即可。
if (firstK < secondK) { //此时剩余长度一定大于k。
res.append(s.substring(firstK, secondK));
}
start += (2 * k);
} }
return res.toString(); return res.toString();
} }