Reverse Words In A String In C#

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"


Solution 1 (Using Loop)

public class Solution {
    public string ReverseWords(string s) {
        string[] array = s.Split(" ");
        string newString = "";
        if (array.Length > 0)
        {
            for (int ai = 0; ai < array.Length; ai++)
            {
                if (!string.IsNullOrEmpty(newString))
                    newString = newString += " ";
                char[] charArray = array[ai].ToCharArray();
                int i = 0, j = charArray.Length - 1;
                for (int k = 0; k < charArray.Length; k++)
                {
                    if (j > i)
                    {
                        char temp = charArray[j];
                        charArray[j] = charArray[i];
                        charArray[i] = temp;
                        j--;
                        i++;

                    }
                }
                newString += new string(charArray);
            }
        }
        return newString;
    }
}

Solution 2 (Using Loop & Linq)

using System;
using System.Linq
public class Solution {
    public string ReverseWords(string s) {
        string[] array = s.Split(" "); 
        if (array.Length > 0)
        {
            for (int ai = 0; ai < array.Length; ai++)
            { 
                char[] newarray = array[ai].ToCharArray();
                Array.Reverse(newarray);
                array[ai] = new string(newarray);
            }
        }
        return string.Join(" ", array);
    }
}

Solution 3 (Using Only Linq)

using System;
using System.Linq;
public class Solution {
    public string ReverseWords(string s) {
        return string.Join(" ", s.Split(" ").Select(x => new String(x.ToCharArray().Reverse().ToArray())));
    }
}


Similar Articles