Algorithm


Problem Name: 557. Reverse Words in a String III

Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

 

Example 1:

Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Example 2:

Input: s = "God Ding"
Output: "doG gniD"

 

Constraints:

  • 1 <= s.length <= 5 * 104
  • s contains printable ASCII characters.
  • s does not contain any leading or trailing spaces.
  • There is at least one word in s.
  • All the words in s are separated by a single space.

Code Examples

#1 Code Example with Java Programming

Code - Java Programming


class Solution {
  public String reverseWords(String s) {
    int idx = 0;
    int n = s.length();
    StringBuilder sb = new StringBuilder();
    int start = 0;
    while (idx  <  n) {
      while (idx < n && s.charAt(idx) != ' ') {
        idx++;
      }
      int curr = idx - 1;
      while (curr >= start) {
        sb.append(s.charAt(curr--));
      }
      if (idx != n) {
        sb.append(" ");
      }
      idx++;
      start = idx;
    }
    return sb.toString();
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "Let's take LeetCode contest"

Output

x
+
cmd
"s'teL ekat edoCteeL tsetnoc"

#2 Code Example with Python Programming

Code - Python Programming


class Solution:
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        j, s_out=0, str()
        for i, char in enumerate(s):
            if i==len(s)-1: s_out+=s[j:i+1][::-1]; return "".join(s_out)
            if char==" ": s_out+=s[j:i][::-1]; j=i+1; s_out+=" "
        return "".join(s_out)
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "Let's take LeetCode contest"

Output

x
+
cmd
"s'teL ekat edoCteeL tsetnoc"

#3 Code Example with C# Programming

Code - C# Programming


using System.Linq;

namespace LeetCode
{
    public class _0557_ReverseWordsInAStringIII
    {
        public string ReverseWords(string s)
        {
            return string.Join(" ", s.Split(' ').Select(w => new string(w.ToCharArray().Reverse().ToArray())));
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "God Ding"

Output

x
+
cmd
"doG gniD"
Advertisements

Demonstration


Previous
#556 Leetcode Next Greater Element III Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#558 Leetcode Logical OR of Two Binary Grids Represented as Quad-Trees Solution in C, C++, Java, JavaScript, Python, C# Leetcode