C# Accepted Solution


  • 0
    L

    Here is my accepted solution in C# with comments explaining what I did.

    static void ReverseWords(string s)
            {
                // Get rid of leading and trailing whitespaces, split by space
                var s_split = s.Trim().Split(' ');
                // Initialize empty string
                var str = "";
    
                // Loop through all except the first word because we don't want
                // space after the last word in the new string
                for (int i = (s_split.Length - 1); i > 0; i--)
                {
                    // If not a null string, add string and space
                    // else add empty string (aka don't make a change)
                    str += s_split[i] != "" ? s_split[i] + " " : "";
                }
                // Add last word without space
                str += s_split[0];
    
                return str;
            }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.