class Solution {
public int lengthOfLastWord(String s) {
// 寻找每个单词开始的位置
int length = s.length();
int[] startPoisition = new int[length];
int[] endPoisition = new int[length];
int startPoisitionIndex = 0;
int endPoisitionIndex = 0;
int lastWordLength = 0;
for(int i = 0; i < length; i++){
char single = s.charAt(i);
// 判断条件,查找字符串中每个单词的开始位置
if((i == 0 || s.charAt(i-1) == 32) && single != 32){
startPoisition[startPoisitionIndex] = i;
startPoisitionIndex += 1;
}
}
for(int i = 0; i < length; i++){
char single = s.charAt(i);
// 判断条件,查找字符串中每个单词的开始位置
if((i == length - 1 || s.charAt(i+1) == 32) && single != 32){
endPoisition[endPoisitionIndex] = i;
endPoisitionIndex += 1;
}
}
if(startPoisitionIndex == 0){
lastWordLength = 0;
}else if(endPoisition[endPoisitionIndex - 1] != startPoisition[startPoisitionIndex - 1]){
lastWordLength = endPoisition[endPoisitionIndex - 1] - startPoisition[startPoisitionIndex - 1] + 1;
}else{
lastWordLength = 1;
}
// startPoisition[startPoisitionIndex - 1] 为最后一个单词开始的位置
return lastWordLength;
}
}
更优的解法
class Solution {
public int lengthOfLastWord(String s) {
int length = s.length();
int lastWordLength = 0;
int lastWordStartPos = 0;
int lastWordEndPos = 0;
// 从后向前遍历,找到最后一个单词的结束位置与开始位置
for(int i = length - 1; i >= 0; i--){
char single = s.charAt(i);
if(single == 32){
if(lastWordLength == 0){
continue;
}else{
break;
}
}else{
lastWordLength += 1;
}
}
return lastWordLength;
}
}