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.

这道题也是基本白给,不多说

class Solution {
    public String reverseWords(String s) {
        if(s == null || s.length() == 0)
            return s;

        int i = 0;
        char[] cs = s.toCharArray();

        while(i < cs.length) {
            while(i < cs.length && cs[i] == ' ')
                i++;

            int j = i;
            while(j < cs.length && cs[j] != ' ')
                j++;

            reverse(cs, i, j - 1);
            i = j;
        }

        return String.valueOf(cs);
    }

    public void reverse(char[] cs, int i, int j) {
        while(i < j) {
            char temp = cs[i];
            cs[i] = cs[j];
            cs[j] = temp;

            i++;
            j--;
        }
    }
}

results matching ""

    No results matching ""