LeetCode58-最后一个单词的长度

题目链接

英文链接:https://leetcode.com/problems/length-of-last-word/

中文链接:https://leetcode-cn.com/problems/length-of-last-word/

题目详述

给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。

如果不存在最后一个单词,请返回 0 。

说明:一个单词是指由字母组成,但不包含任何空格的字符串。

示例:

1
2
输入: "Hello World"
输出: 5

题目详解

这题比较简单,先跳过最后的空格,再统计最后一个单词的长度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class LeetCode_00058 {

public int lengthOfLastWord(String s) {
int res = 0;
int i = s.length() - 1;
// 跳过最后的空格
for (; i >= 0 && s.charAt(i) == ' '; --i);
// 统计最后一个单词的长度
for (; i >= 0 && s.charAt(i) != ' '; --i) {
++res;
}
return res;
}
}