aboutsummaryrefslogtreecommitdiff
path: root/length_last_word.py
diff options
context:
space:
mode:
authorjack <[email protected]>2024-06-14 13:13:15 -0600
committerjack <[email protected]>2024-06-14 13:13:15 -0600
commitd343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch)
tree96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /length_last_word.py
downloadleetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz
leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip
initial
Diffstat (limited to 'length_last_word.py')
-rw-r--r--length_last_word.py29
1 files changed, 29 insertions, 0 deletions
diff --git a/length_last_word.py b/length_last_word.py
new file mode 100644
index 0000000..c467206
--- /dev/null
+++ b/length_last_word.py
@@ -0,0 +1,29 @@
+# 58. Length of Last Word
+
+"""
+given a string 's' consisting of words and spaces, return the length of the
+last word in the string. a word is a maximal substring consisting of non
+space characters only.
+"""
+
+
+class Solution(object):
+ def lengthOfLastWord(self, s):
+ """
+ :type s: str
+ :rtype: int
+ """
+ end = len(s) - 1
+ while end > 0 and s[end] == " ":
+ end -= 1
+ begin = end
+ while begin >= 0 and s[begin] != " ":
+ begin -= 1
+ return end - begin
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.lengthOfLastWord("Hello World"))
+ print(obj.lengthOfLastWord(" fly me to the moon "))
+ print(obj.lengthOfLastWord("luffy is still joyboy"))