1. 题目原址
https://leetcode.com/problems/length-of-last-word/
2. 题目描述
3. 题目大意
给定一个字符串,返回这个字符串中最后一个单词的长度
4. 解题思路
- 首先判断字符串的长度和是否为空
- 使用内置方法 trim来去掉空格。
- 使用lastIndexOf方法来找到最后一个单词的下标位置。
- 如果找到的下标位置不为 - 1 就说明找到了最后一个单词的下标位置。
- 如果找到的下标位置为 -1 就说明这个字符串中只有一个单词。
5. AC代码
class Solution {
public int lengthOfLastWord(String s) {
if(s == null || s.length() == 0)
return 0;
s = s.trim();
int length = s.length();
int index = s.lastIndexOf(' ');
int count = 0;
if(index != -1) {
while(index ++ < length)
count++;
}else {
index = 0;
while(index ++ < length)
count++;
count ++;
}
return count - 1;
}
}