[C#] Short solution


  • 0
    G
    public class Solution {
        public string ReverseWords(string s) {
            List<string> ns = new List<string>();
            foreach(string w in s.Split(' '))
            {
                ns.Add(new string(w.ToCharArray().Reverse().ToArray()));
            }
            return String.Join(" ", ns);
        }
    }
    

    Explanation:

    • Instantiate an arraylist
    • Loop through each substring of original string (split to an array)
    • Convert substring to array of char, reverse this array, convert to normal array and then into a string
    • Add each reversed substring back to our array variable
    • Join the arraylist back into a single string

Log in to reply
 

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