58. 最后一个单词的长度

转载自Leet Code

题目描述

给定一个仅包含大小写字母和空格' '的字符串s,返回其最后一个单词的长度。 如果字符串从左向右滚动显示,那么最后一个单词就是最后出现的单词。 如果不存在最后一个单词,请返回 0 。 说明:一个单词是指仅由字母组成、不包含任何空格字符的 最大子字符串

示例 1:

输入:s = "Hello World" 输出:5

示例 2:

输入:s = " fly me to the moon " 输出:4

示例 3:

输入:s = "luffy is still joyboy" 输出:6


我的代码

{.line-numbers}
1
2
3
4
5
6
7
8
9
10
class MySolution58 
{
public int lengthOfLastWord(String s)
{
if (s==null||s.trim().length()<=0||s.length()<=0) return 0; //注意trim()

String []strs = s.split(" ");
return strs[strs.length-1].length();
}
}