ALGORITHM
1 min readMay 10, 2021
TIL 2021.05.07
Solved in: Javascript and Python
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:
- 1 <= s.length <= 104
- s consists of only English letters and spaces ‘ ‘.
Solution: JavaScript
/**
* @param {string} s
* @return {number}
*/
var lengthOfLastWord = function(s) {
const arr = s.split(" ")
let words = []
for(let i = 0; i < arr.length; i++){
if(arr[i] !== ""){
words.push(arr[i])
}
}
if(words.length > 1){
return words[words.length-1].length
} else if (words.length === 1){
return words[0].length
} else {
return 0
}
};
Solution: Python
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
words = s.split()
if len(words) >= 1:
return len(words[len(words) - 1])
else:
return 0