// 方法1
public String reverseWords(String s) {
String[] words = s.split(" ");
StringBuilder sb = new StringBuilder();
for (String w : words) {
sb.append(new StringBuilder(w).reverse().toString() + " ");
}
return sb.toString().trim();
}
// 方法2 + two pointers
public String reverseWords(String s) {
int lastEnd = -1;
char[] arr = s.toCharArray();
int len = s.length();
for (int i = 0; i <= len; i++) {
if (i == len || arr[i] == ' ') {
int start = lastEnd + 1;
int end = i - 1;
while (start < end) {
char temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
lastEnd = i;
}
}
return new String(arr);
}
// 方法2 + 用StringBuilder储存颠倒过后的单词
public String reverseWords(String s) {
StringBuilder result = new StringBuilder();
int lastSpaceIndex = -1;
for (int strIndex = 0; strIndex < s.length(); strIndex++) {
if ((strIndex == s.length() - 1) || s.charAt(strIndex) == ' ') {
int reverseStrIndex = (strIndex == s.length() - 1) ? strIndex : strIndex - 1;
for (; reverseStrIndex > lastSpaceIndex; reverseStrIndex--) {
result.append(s.charAt(reverseStrIndex));
}
if (strIndex != s.length() - 1) {
result.append(' ');
}
lastSpaceIndex = strIndex;
}
}
return new String(result);
}