题目描述

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.

解法一

思路

注意这题要求反转的是字符串中的每个单词,并且反转后单词整体在字符串中的相对位置不变。

这个做法就很简单了,对于每个字符串,只需要定位到其开始index和结束index,然后反转单词就好了。对于定位,就是经典的双指针法加一些边界条件判断了,而反转就是最基本的那个了。

Python

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        length = len(s)
        str = list(s)
        i = 0
        while i < length and str[i] == ' ':
            i += 1
        j = i
        while j < length:
            while j < length and str[j] != ' ':
                j += 1
            str[i:j] = s[i:j][::-1]
            while j < length and str[j] == ' ':
                j += 1
            i = j
        return ''.join(str)

Java

public class Solution {
    public String reverseWords(String s) {
        int length = s.length();
        char[] str = s.toCharArray();
        int i = 0;
        while (i < length && str[i] == ' ') {
            i++;
        }
        int j = i;
        while (j < length) {
            while (j < length && str[j] != ' ') {
                j++;
            }
            int low = i;
            int high = j - 1;
            while (low < high) {
                char temp = str[low];
                str[low] = str[high];
                str[high] = temp;
                low++;
                high--;
            }
            while (j < length && str[j] == ' ') {
                j++;
            }
            i = j;
        }
        return new String(str);
    }
}

C++

class Solution {
public:
    string reverseWords(string s) {
        int length = s.length();
        int i = 0;
        while (i < length && s[i] == ' ') {
            i++;
        }
        int j = i;
        while (j < length) {
            while (j < length && s[j] != ' ') {
                j++;
            }
            int low = i;
            int high = j - 1;
            while (low < high) {
                char temp = s[low];
                s[low] = s[high];
                s[high] = temp;
                low++;
                high--;
            }
            while (j < length && s[j] == ' ') {
                j++;
            }
            i = j;
        }
        return s;
    }
};