Given a string s consists of upper/lower-case alphabets and empty space characters ' '
, return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
For example,
Given s = "Hello World"
,
return 5
.
返回最后一个单词的长度 由于之前做过 reverse words 这题是其基础题 思路是从后面开始找第一个非空格字符 再向前找空格 最后确认长度 代码如下:
public class Solution {
public int lengthOfLastWord(String s) {
if(s.length()==0)return 0;
int lastend=0;
for(int i=s.length()-1;i>=0;i--){
if(s.charAt(i)!=' ') {
lastend=i+1;
break;
}
}
if(lastend==0)return 0;
for(int i=lastend-1;i>=0;i--){
if(s.charAt(i)==' ')return lastend-i-1;
}
return lastend;
}
}