题目:
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.
分析:思路:遍历,遇到字母开始计数,遇到空格将计数清零,再从头开始计数。
考虑特殊情况三种情况:
1.整个字符串为空时
2.字符串由无数的空格组成时
3.字符串最后以空格结尾时
知识点总结:
1. if(s.substring(i,i+1).equals(" ")) //用来判断字符串s的第i个字符是否是空格
2.if (s.trim().isEmpty()) //trim的作用是去掉字符串左右两侧的空格,中间的干涉不了,用于检测字符串是不是由任意个空格组成
Accepted代码如下:
public int lengthOfLastWord(String s) {
int num=0;
int remember=0;//用来记住空格前面的那个字符,防止空格出现在最后
if(s.length()==0)
{
return 0;
}
else if (s.trim().isEmpty()) {
return 0;//判断整个字符串是否全部为空格组成
}
else {
for(int i=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{return num;}
}
}
Length of Last Word(LeetCode)#58
原文:http://www.cnblogs.com/jennifer8385/p/4858789.html