LeetCode #58 Length of Last Word Solution & Explanation

LeetCode Problem

Given a string s consisting of words and spaces, return the length of the last word in the string.

word is a maximal substring consisting of non-space characters only.

LeetCode #58 Examples
LeetCode #58 Constraints

Solution

This question is easy to understand, Let’s have a try.

First, let us iterate the string s

C# Solution

Solution1 – iteration

Two things need to be checked, one is whitespace and the other is the count ( cnt )

If the count isn’t greater than 0, that means we haven’t find a word.

public class Solution {
    public int LengthOfLastWord(string s) {
        
        int cnt = 0;
        
        for(int i = s.Length-1;i>=0;i--)
        {
            if(Char.IsWhiteSpace(s[i]))
            {
                if(cnt>0)
                {
                    return cnt;    
                }
                continue;
            }
            
            cnt+=1;
        }
        return cnt;
    }
}

Solution2 – Split function

The second solution uses C# Built-in function – Split

We split the string s by whitespace first, than run an iteration of the split result array

If we find one of the iterate item is not empty, than it is the last word ( iterate from the end of array )

public class Solution {
    public int LengthOfLastWord(string s) {
        string[] tmp = s.Split(' ');         
        string tmpStr;
        
        for(int i = tmp.Length-1; i>=0; i--)  
        {
            tmpStr = tmp[i];
            if(!String.IsNullOrEmpty(tmpStr)) 
            {
                return tmpStr.Length;
            }
        }
        return 0;                            
    }
}

Solution2.1 – Split function with pre-action (Trim)

Look at the above solution, we can find out, if we can remove whitespace from the end of s, than we can get the length of last element of array easier.

We can find built-in String.Trim( ) function can help us remove the whitespace

  • Trim( ) ➡ remove start and end
  • TrimEnd( )
  • TrimStart( )

public class Solution {
    public int LengthOfLastWord(string s) {
        s = s.TrimEnd();                 //or you can use Trim()
        string[] tmp = s.Split(' ');
        return tmp[tmp.Length-1].Length; 
    }
}

Solution2.2 – Split function > Built-in parameter

When I thought that the question has been solve successfully …

I found a parameter of split in official document ( StringSplitOptions )

And one of it – 【RemoveEmptyEntries】➡ Omit array elements that contain an empty string from the result.

That is actually what we want, isn’t it !!!

public class Solution {
    public int LengthOfLastWord(string s) {
        string[] tmp = s.Split(' ',StringSplitOptions.RemoveEmptyEntries);
        return tmp[tmp.Length-1].Length;
    }
}

Java Solution

Solution1

class Solution {
    public int lengthOfLastWord(String s) {
        int cnt = 0;
        
        for(int i = s.length()-1;i>=0;i--)
        {
            if(s.charAt(i)==' ')
            {
                if(cnt>0)
                {
                    return cnt;    
                }
                continue;
            }
            
            cnt+=1;
        }
        return cnt;
    }
}

Runtime : 0ms、0ms、0ms

Solution2String.trim()

class Solution {
    public int lengthOfLastWord(String s) {
        s = s.trim();
        String[] arr =  s.split("\\s+");
        
        return arr[arr.length-1].length();
    }
}

Python3 Solution

Solution1

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        cnt = 0;
        for i in range(len(s)-1,-1,-1):
            if(s[i]== ' '):
                if cnt>0 :
                    return cnt
                continue
            cnt+=1;
        return cnt

Solution2Python strip ( similar to C# Trim function )

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        s = s.rstrip()  #or strip
        return len(s.split()[-1])

Runtime : 35ms、30ms、36ms

JavaScript Solution

Solution1

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLastWord = function(s) {
    var cnt = 0;

    for(var i = s.length-1;i>=0;i--)
    {
        if(s[i]==' ')
        {
            if(cnt>0)
            {
                return cnt;    
            }
            continue;
        }

        cnt+=1;
    }
    return cnt;
};

Runtime : 72ms、69ms、73ms

Solution2String.trim()

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLastWord = function(s) {
    s = s.trim();
    var arr = s.split(' ');
    return arr[arr.length-1].length;
};

Runtime : 64ms、78ms、81ms


Conclusion

🧡If my solution helps, that is my honor!

If you got any problem about the explanation or you need other programming language solution, please feel free to let me know (either leave a comment or contact me by Messenger is ok!)

The problem link : Length of Last Word – LeetCode

Latest Post

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *