C# solution, using string.Trim() || string.Split(' ')


  • 0
    F
    public class Solution {
        public int LengthOfLastWord(string s) {
            /*
            string[] words = s.Split(' ');
            int len = words.Length;
            
            for(int i= len-1; i>=0;i--){
                if(words[i]!="")
                    return words[i].Length;
            }
            return 0;
            */
            
            s=s.Trim();
            var arr = s.ToCharArray();
            int count=0;
            for(int i=s.Length-1;i>=0;i-- ){
                if(arr[i]!=' ')
                    count++;
                else break;
            }
            return count;
        }
    }
    

Log in to reply
 

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