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
.
代码如下:
public class Solution {
public int lengthOfLastWord(String s) {
int num = 0;
int tmp = 0;
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
String space = " ";
String str = ch + "";
if(!str.equals(space)){
tmp++;
num = tmp;
}
else{
tmp = 0;
}
}
return num;
}
}
第一次提交还是没能通过的。
失败的测试用例为“a ”.
我的返回值为0.而其实最后一个单词是a。
所以需要多加一个变量num. 来记录下最后一个单词的字母数。