![[LeetCode] 58. Length of Last Word java](/default/index/img?u=aHR0cHM6Ly9wMC5waXFzZWxzLmNvbS9wcmV2aWV3LzgwLzM5MC80NTEvaGFuZHMtc2Nhcnktc2lsaG91ZXR0ZS1ob3Jyb3IuanBn&w=245&h=&w=700)
/**58. Length of Last
Word
* @param s
* @returnint
*/
public int lengthOfLastWord(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int end = s.length() - 1;
while(end >= 0 && s.charAt(end) == ' ') {
end--;
}
int start = end;
while(start >= 0 && s.charAt(start) != ' ') {
start--;
}
return end-start;
}
//顺序!!!先判断index是否有效,在判断值