Sharing my C# solution using build in trim and split


  • 1
    Y
     //trim  the string
        
        s = s.Trim();
        
        var wordsListWithSpace = s.Split(' ');
        var newWordList=new List<string>();
        
        for(int i=0; i<wordsListWithSpace.Length;i++ )
        {
            var temp=wordsListWithSpace[i].Trim();
            if(!string.IsNullOrEmpty(temp))
            {
                newWordList.Add(temp);
            }
        }
        
        var resultStringBuilder =new StringBuilder();
        
        for(int i=0; i < newWordList.Count; i++)
        {
            resultStringBuilder.Append(newWordList[newWordList.Count - i - 1]);
            resultStringBuilder.Append(" ");
        }
    
        return resultStringBuilder.ToString().Trim();

Log in to reply
 

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