Question
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:
- <= s.length <= 104
- s consists of only English letters and spaces ' '
Let's Go!
Solve by using PREP.
- P - One parameter. A string s
- R - Return number that represents length of last word in s
- E - Examples provided by question. (See Above)
- P - See Below
var lengthOfLastWord = function(s) {
// remove whitespace & split s by empty space ' '
// return the length of the last element of the array or 0
};
Translate into code...
var lengthOfLastWord = function(s) {
// remove whitespace & split s by empty space ' '
const words = s.trim().split(' ')
// return the length of the last element of the array or 0
return words.length > 0 ? words[words.length-1].length : 0
};
Conclusion
& Remember... Happy coding, friends! =)
Top comments (0)