Length of Last Word | Leetcode #58 | Easy
In this post I will discuss the solution to the leetcode problem — Length of Last Word.
Problem:
Given a string s
consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0
.
A word is a maximal substring consisting of non-space characters only.
Example 1:
Input: s = "Hello World"
Output: 5
Example 2:
Input: s = " "
Output: 0
Constraints:
1 <= s.length <= 104
s
consists of only English letters and spaces' '
.
Solution:
This is one of the simplest leetcode problems ever. There are multiple approaches to solve this problem and one of them is to split the string with space(“ ”)
as the delimiter and return the last element of the array. Depending on whether the input was split into multiple words or not, return 0 or word from the words
array as the output.
Here is how the code looks like —
class Solution {
public int lengthOfLastWord(String s) {
String[] words = s.split(" ");
return words.length == 0 ? 0 : words[words.length - 1].length();
}
}
Hope this helps! Happy coding! 🙂
If you think the solution can be improved or misses something, feel free to comment. There is always some room for improvement.
Find the solutions to the leetcode problems here — https://github.com/rishikeshdhokare/leetcode-problems