Created
September 15, 2020 10:57
-
-
Save kuntalchandra/bc8c66b8ec0749ab7ac7870e1450ae4d to your computer and use it in GitHub Desktop.
Length of Last Word
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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. | |
Example: | |
Input: "Hello World" | |
Output: 5 | |
""" | |
class Solution: | |
def lengthOfLastWord(self, s: str) -> int: | |
if not s: | |
return 0 | |
s = s.strip() | |
res = 0 | |
n = len(s) - 1 | |
for i in range(n, -1, -1): | |
if s[i] == " ": | |
return res | |
res += 1 | |
return res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment