题目:
Given a stringsconsists of upper/lower-case alphabets and empty space characters' ', return the length of lastWordin 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,
Givens="Hello World",
return5.
分析:
思路:遍历,遇到字母开始计数,遇到空格将计数清零,再从头开始计数。
考虑特殊情况三种情况:
1.整个字符串为空时
2.字符串由无数的空格组成时
3.字符串最后以空格结尾时
知识点总结:
1. if(s.substring(i,i+1).equals(" ")) //用来判断字符串s的第i个字符是否是空格
2.if (s.trim().isEmpty()) //trim的作用是去掉字符串左右两侧的空格,中间的干涉不了,用于检测字符串是不是由任意个空格组成
Accepted代码如下:
publicintlengthOfLastWord(String s) {intnum=0;intremember=0;//用来记住空格前面的那个字符,防止空格出现在最后if(s.length()==0)
{return0;
}elseif(s.trim().isEmpty()) {return0;//判断整个字符串是否全部为空格组成}else{for(inti=0;i<s.length();i++){
num++;//用来计数,每次遇到空格则重新计数if(num!=1)
{
remember=num;}if(s.substring(i,i+1).equals(" ")){
num=0;//遇到空格置零即可}
}if(num==0){return(remember-1);
}else{returnnum;}
}
}