AcWing 77. 翻转单词顺序
原题链接
中等
作者:
菜是原罪_1
,
2021-03-30 09:50:09
,
所有人可见
,
阅读 236
class Solution {
public String reverseWords(String s) {
char[] chars = s.toCharArray();
reverse(chars, 0, chars.length);
int start = 0;
for (int i = 0; i <= chars.length; i++) {
// 字符串到头了,或者遇到了' '则进行翻转。注意!i == chars.length需要先判断!不让会数组越界异常!
if (i == chars.length || chars[i] == ' ') {
reverse(chars, start, i);
start = i + 1;
}
}
return new String(chars);
}
public void reverse(char[] chars, int start, int length) {
for (int i = start, j = length - 1; i <= j; i++, j--) {
char tmp = chars[i];
chars[i] = chars[j];
chars[j] = tmp;
}
}
}