题:https://leetcode.com/problems/length-of-last-word/
题目大意
对于一字符串,找出最后一个单词的长度。
单词使用空格来分割,字符串尾部的 ‘ ’ 忽略。
思路
分为两步:
1.确定最后一个单词的尾部,2.找该单词的头部。
找头部有两种:1.最后一个单词的前面为空格。2字符串只有一个单词。
class Solution {
public int lengthOfLastWord(String s) {
int N = s.length();
if(N == 0)
return 0;
int index = N - 1;
while(index >=0 && s.charAt(index) == ' '){
index--;
N--;
}
while(index >=0 && s.charAt(index) != ' '){
index--;
}
return N - 1 - index;
}
}