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.
Tip: 一个单词的意思是不包含空格的字符序列
public class LenthOfLastWordSolution {
public int lengthOfLastWord(String s) {
/**
* 简单的模拟题
* 从字符串尾部开始遍历
*/
boolean startFlag = false;
int result = 0;
int len = s.length();
for (int i = len - 1; i >= 0; i--) {
if (s.charAt(i) == ' ' && startFlag) {
//结束
break;
}
if (s.charAt(i) != ' ' && !startFlag) {
//最后一个单词开始位置
startFlag = true;
}
if (s.charAt(i) != ' ' && startFlag) {
//计数
result++;
}
}
return result;
}
}