给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中 最后一个 单词的长度。
单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。
示例 1:
输入:s = “Hello World”
输出:5
解释:最后一个单词是“World”,长度为5。
示例 2:
输入:s = " fly me to the moon "
输出:4
解释:最后一个单词是“moon”,长度为4。
示例 3:
输入:s = “luffy is still joyboy”
输出:6
解释:最后一个单词是长度为6的“joyboy”。
C代码:strtok()
int lengthOfLastWord(char * s){
char buff[strlen(s) + 1];
strcpy(buff, s);
char* str = strtok(buff, " "); // strtok入参必须是字符数组、字符串
int len = 0;
while (str != NULL) {
len = strlen(str);
str = strtok(NULL, " ");
}
return len;
}
Java代码1:
public int lengthOfLastWord(String s) {
int j = s.length() - 1;
while (s.charAt(j) == ' ') {
--j;
}
int ans = 0;
while (j >= 0 && s.charAt(j) != ' ') {
++ans;
--j;
}
return ans;
}
Java代码2:API
public int lengthOfLastWord(String s) {
s = s.trim();
return s.length() - 1 - s.lastIndexOf(' ');
}