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"

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

Thought

Split the given string by space, for each item we traverse the word from both sides to exchange the letter. Finally join the reversed-words with space.

Solution

public class Solution {
    public String reverseWords(String s) {
        String[] words = s.split(" ");
        for (int i = 0; i < words.length; i++) {
            // reverse the current string
            char[] c = words[i].toCharArray();
            int l = 0, r = c.length - 1;
            while (l < r) {
                char temp = c[l];
                c[l++] = c[r];
                c[r--] = temp;
            }
            words[i] = String.valueOf(c);
        }

        return String.join(" ", words);
    }
}

results matching ""

    No results matching ""