1
+ """
2
+ Given a string s consisting of some words separated by some
3
+ number of spaces, return the length of the last word in
4
+ the string.
5
+
6
+ A word is a maximal substring consisting of non-space
7
+ characters only.
8
+
9
+ Example 1:
10
+ Input: s = "Hello World"
11
+ Output: 5
12
+ Explanation: The last word is "World" with length 5.
13
+
14
+ Example 2:
15
+ Input: s = " fly me to the moon "
16
+ Output: 4
17
+ Explanation: The last word is "moon" with length 4.
18
+
19
+ Example 3:
20
+ Input: s = "luffy is still joyboy"
21
+ Output: 6
22
+ Explanation: The last word is "joyboy" with length 6.
23
+
24
+ Constraints:
25
+ * 1 <= s.length <= 10^4
26
+ * s consists of only English letters and spaces ' '
27
+ * There will be at least one word in s
28
+ """
29
+
30
+ class Solution :
31
+ # O(n) approach, we are starting from the beginning
32
+ #def lengthOfLastWord(self, s: str) -> int:
33
+ # word = ""
34
+ # for i in range(len(s)):
35
+ # if word != "" and s[i-1] == " " and s[i] != " ":
36
+ # word = ""
37
+ #
38
+ # if s[i] != " ":
39
+ # word += s[i]
40
+ #
41
+ # return len(word)
42
+
43
+ # O(n) approach, start from the end
44
+ # it will be O(n) if the string consist of a single word
45
+ # (with or without spaces at the end)
46
+ # otherwise it will be O(k) where k = length of last word
47
+ # + the number of space after the last word
48
+ def lengthOfLastWord (self , s : str ) -> int :
49
+ c = 0
50
+ for i in range (len (s )- 1 , - 1 , - 1 ):
51
+ if s [i ] != " " :
52
+ c += 1
53
+
54
+ if c > 0 and s [i ] == " " :
55
+ break
56
+
57
+ return c
0 commit comments