Reverse Words in a String III
💻 coding

Reverse Words in a String III

1 min read 121 words
1 min read
ShareWhatsAppPost on X
  • 1The task is to reverse characters in each word of a sentence while preserving whitespace and word order.
  • 2An example input is 'Let's take LeetCode contest', which outputs 's'teL ekat edoCteeL tsetnoc'.
  • 3The provided solution has a time complexity of O(n) and a space complexity of O(n).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to reverse characters in each word of a sentence while preserving whitespace and word order."

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 a single space and there will not be any extra space in the string.

Solution:

using System;
using System.Collections.Generic;
using System.Text;

namespace LeetCode.AskGif.Easy.String
{
 public class ReverseWordsSoln
 {
 public string ReverseWords(string s)
 {
 var strArr = s.Split(" ");
 var str = new StringBuilder();
 foreach (var item in strArr)
 {
 for (int i = item.Length-1; i >= 0; i--)
 {
 str.Append(item[i]);
 }
 str.Append(" ");
 }
 return str.ToString().Trim();
 }
 }
}

Time Complexity: O(n)

Space Complexity: O(n)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 11 May 2020 · 1 min read · 121 words

Part of AskGif Blog · coding

You might also like