DAY 12
0

58. Length of Last Word

Question

Given a string `s` consisting of some words separated by some number of spaces, return the length of the last word in the string.

A word is a maximal substring consisting of non-space characters only.

Example

Example1

``````Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.
``````

Example2

``````Input: s = "   fly me   to   the moon  "
Output: 4
Explanation: The last word is "moon" with length 4.
``````

Example3

``````Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.
``````

Constraints

• `1 <= s.length <= 10^4`
• `s` consists of only English letters and spaces `' '`.
• There will be at least one word in `s`.

解題

Think

• 很簡單，就切割字串，然後找到最後一個字，再回傳他的長度。
• Python的話，先用`strip()`去除原始字串前後的空白去掉，再用`split()`以空白切割字串，會存在`list_s`中，最後index可以用`-1`找到最後一個字，再回傳長度就好。

Code

Python

``````class Solution:
def lengthOfLastWord(self, s: str) -> int:
list_s = s.strip().split(" ")
# print(list_s)
return len(list_s[-1])
``````

C

``````int lengthOfLastWord(char * s){
char *token;
char *last_word;
token = strtok(s, " ");

while( token != NULL ) {
// printf("%s\n", token);
last_word = token;
// printf("%s\n", last_word);
token = strtok(NULL, " ");
if (token == NULL){
return strlen(last_word);
}
}

return 1;
}
``````

Result

• Python

• C

30天 Leetcode解題之路30