Formatted question description: https://leetcode.ca/all/557.html

557. Reverse Words in a String III

Level

Easy

Description

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.

Solution

Since words are split by spaces, find the start index and the end index of each word, and reverse the characters from the start index and the end index.

/**
public class Reverse_Words_in_a_String_III {

    // ref: https://leetcode.com/articles/reverse-words-in-a-string-iii/
    public class Solution {
        public String reverseWords(String input) {
            final StringBuilder result = new StringBuilder();
            final StringBuilder word = new StringBuilder();
            for (int i = 0; i < input.length(); i++) {
                if (input.charAt(i) != ' ') {
                    word.append(input.charAt(i));
                } else {
                    result.append(word.reverse());
                    result.append(" ");
                    word.setLength(0);
                }
            }
            result.append(word.reverse()); // @note: last one
            return result.toString();
        }
    }

    public class Solution2 {
        public String reverseWords(String s) {
            String words[] = s.split(" ");
            StringBuilder res = new StringBuilder();
            for (String word : words) {
                res.append(new StringBuffer(word).reverse().toString() + " ");
            }
            return res.toString().trim();
        }
    }
}

All Problems

All Solutions