大家好,我是毛毛。ヾ(´∀ ˋ)ノ
廢話不多說開始今天的解題Day~
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.
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.
Input: s = " fly me to the moon "
Output: 4
Explanation: The last word is "moon" with length 4.
Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.
1 <= s.length <= 10^4
s
consists of only English letters and spaces ' '
.s
.首先先簡單的翻譯一下題目
給一個字串,其中組成的字會由數量不一的空白隔開,回傳最後一個的字的長度。
作法大致上是這樣
strip()
去除原始字串前後的空白去掉,再用split()
以空白切割字串,會存在list_s
中,最後index可以用-1
找到最後一個字,再回傳長度就好。class Solution:
def lengthOfLastWord(self, s: str) -> int:
list_s = s.strip().split(" ")
# print(list_s)
return len(list_s[-1])
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;
}
Python
C
大家明天見