一【题目类别】
- 字符串
二【题目难度】
- 简单
三【题目编号】
- 58.最后一个单词的长度
四【题目描述】
- 给你一个字符串 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”。
六【解题思路】
- 要反着想,从后向前搜索
- 先把所有的‘ ’都“过滤”掉
- 然后再计算字符串的长度
- 最后返回结果即可
七【题目提示】
- 1 < = s . l e n g t h < = 1 0 4 1 <= s.length <= 10^4 1<=s.length<=104
- s 仅有英文字母和空 格 ′ ′ 组成 s 仅有英文字母和空格 '\ ' 组成 s仅有英文字母和空格′ ′组成
- s 中至少存在一个单词 s 中至少存在一个单词 s中至少存在一个单词
八【时间频度】
- 时间复杂度: O ( n ) O(n) O(n),其中 n n n 是字符串长度
- 空间复杂度: O ( 1 ) O(1) O(1)
九【代码实现】
- Java语言版
package String;
public class p58_LengthOfLastWord {
public static void main(String[] args) {
String s = "Hello World";
int res = lengthOfLastWord(s);
System.out.println("res = " + res);
}
public static int lengthOfLastWord(String s) {
int res = 0;
int index = s.length() - 1;
while (index >= 0 && s.charAt(index) == ' ') {
index--;
}
while (index >= 0 && s.charAt(index) != ' ') {
res++;
index--;
}
return res;
}
}
- C语言版
#include<stdio.h>
#include<stdlib.h>
int lengthOfLastWord(char * s)
{
int res = 0;
int index = strlen(s) - 1;
while (index >= 0 && s[index] == ' ')
{
index--;
}
while (index >= 0 && s[index] != ' ')
{
res++;
index--;
}
return res;
}
/*主函数省略*/
十【提交结果】
-
Java语言版
-
C语言版