LeetCode 58. Length of Last Word
考点 | 难度 |
---|---|
String | Easy |
题目
Given a string s
consisting of some words separated by some number of spaces, return the length of the last word in the string.
A word is a maximal substring consisting of non-space characters only.
思路
最开始以为需要分词,其实只需要从右向左移动找到第一个不是空格的位置和这之后第一个是空格的位置即可。
答案
public int lengthOfLastWord(String s) {
int len=s.length(), lastLength=0;
while(len > 0 && s.charAt(len-1)==' '){
len--;
}
while(len > 0 && s.charAt(len-1)!=' '){
lastLength++;
len--;
}
return lastLength;
}