This Wednesday we will be looking at Length of Last Word. Another common interview question that shouldnt be too challenging. As always, I suggest you give it a try or following along at: https://leetcode.com
Question
“Given a string s consists of upper/lower-case alphabets and empty space characters ‘ ‘, return the length of last word (last word means the last appearing word if we loop from left to right) in the string.
If the last word does not exist, return 0.
Note: A word is defined as a maximal substring consisting of non-space characters only.”
Code
We will solve this problem in 3 steps. Step 1. Removing trailing white space on either side of the string. We can easily do this with the Java trim() function.
We need to remove white space for a few edge cases. For examples the string: ” Hello world “. Would cause some issues for our algorithm which requires finding the last space prior to the last word in the string.
Step 2. Finding the index of the last instance of space in the string. We will make use of another function here, lastIndexOf().
After find the index we need to add one. This will put us at the start of the last word. We know we can’t go out of bound since we trimmed the white space.
Step 3. Return the length whole string, minus the index of the last space found, plus one.
The difference between the lastIndex+1 and the end of the string will just be the length of the last word.
For example: ” Hello world ” -> calling trim -> “Hello World” -> finding index of last ” ” (5) + 1 = 6. -> s.length (11) – 6 = 5! The length of “World”!
Tests
As always with LeetCode we can submit our solution to have it run for a variety of tests. Success! We passed!
For more tech blogs, subscribe to the code_marks news letter: http://eepurl.com/gZCMQz
3 Comments
Some truly good content on this web site , thanks for contribution.
Way cool! Some very valid points! I appreciate you penning this write-up plus the rest of the website is very good.
Im grateful for the blog. Cool.