一.题目描述
给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/
二.代码
public String reverseWords(String s) {
char[] array = s.toCharArray();
int start = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == ' ') {
reverse(array, start, i - 1);
start = i + 1;
}
}
reverse(array, start, array.length - 1);
return new String(array);
}
private void reverse(char[] array, int l, int r) {
while (l < r) {
char temp = array[l];
array[l] = array[r];
array[r] = temp;
l += 1;
r -= 1;
}
}