Description:
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.
Example:
Input: "Hello World"
Output: 5
题意:给定一个字符串,字符串中的单词用空格分割,要求返回字符串中最后一个单词的长度;
解法:我们可以利用到String中的一个lastIndexof方法,用于查找最后一个出现的指定字符,但是这里要注意的是给出的字符串可能在末尾有空格,所以需要先去掉此空格;
class Solution {
public int lengthOfLastWord(String s) {
s = s.trim();
int index = s.lastIndexOf((int)' ');
return index == -1 ? s.length() - 0 : s.length() - index - 1;
}
}