【问题描述】
Given a string s consists of upper/lower-case alphabets and empty space characters ' '
, return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
For example,
Given s = "Hello World"
,
return 5
.
【思路】
1、如果s为null,则返回0
2、处理单个单词的情况,返回s的长度
3、查找最后一个空格,计算后缀长度
#:运算前需先去除s两端的空格。
【code】
public class Solution {
public int lengthOfLastWord(String s) {
s = s.trim();
if (s == null) {
return 0;
}
if (s.lastIndexOf(" ") == -1) {
return s.length();
}
return s.length() - s.lastIndexOf(" ") - 1;
}
}