Formatted question description:

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.


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:
        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) != ' ') {
                    } else {
                        result.append(" ");
                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();
  • Todo
  • class Solution(object):
      def reverseWords(self, s):
        :type s: str
        :rtype: str
        s = s.split()
        for i, word in enumerate(s):
          s[i] = word[::-1]
        return " ".join(s)

All Problems

All Solutions