Description
https://leetcode.com/problems/length-of-last-word/
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 <= 104sconsists of only English letters and spaces' '.
Explanation
Split the string and find the length of the last word. If the string can’t be spitted, return 0.
Python Solution
class Solution:
def lengthOfLastWord(self, s: str) -> int:
if not s:
return 0
words = s.split()
if not words:
return 0
last_word = words[-1]
return len(last_word)
- Time Complexity: O(N).
- Space Complexity: O(1).