題目:
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
AC:
public String reverseWords(String s) {
if (s == null || s.length() < 2) {
return s;
}
int begin = 0;
int end = 0;
char[] words = s.toCharArray();
int index = s.indexOf(' ');
while (index > 0) {
reverseWord(words, begin, index - 1);
begin = index + 1;
index = s.indexOf(' ', begin);
}
reverseWord(words, begin, s.length() - 1);
return String.valueOf(words);
}
private void reverseWord(char[] words, int begin, int end) {
while (end > begin) {
char tmp = words[end];
words[end] = words[begin];
words[begin] = tmp;
end--;
begin++;
}
}