557. Reverse Words in a String III
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"
解法
先转为字符串数组,没遇到一个空格,将前一个空格和现在的空格之间的字符串反转一次。因为最后一个单词结尾不会有空格,所以单独再反转一次。
public class Solution {
public String reverseWords(String s) {
if (s == null || s.length() == 0) {
return "";
}
char[] charArray = s.toCharArray();
int i = 0;
for (int j = 0; j < charArray.length; j++) {
if (charArray[j] == ' ') {
reverse(charArray, i, j - 1);
i = j + 1;
}
}
reverse(charArray, i, charArray.length - 1);
return new String(charArray);
}
public void reverse(char[] s, int left, int right) {
while (left < right) {
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
}