題目:
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
.
分析:
思路:遍歷,遇到字母開始計數(shù),遇到空格將計數(shù)清零,再從頭開始計數(shù)。
考慮特殊情況三種情況:
1.整個字符串為空時
2.字符串由無數(shù)的空格組成時
3.字符串最后以空格結(jié)尾時
知識點總結(jié):
1. if(s.substring(i,i+1).equals(" ")) //用來判斷字符串s的第i個字符是否是空格
2.if (s.trim().isEmpty()) //trim的作用是去掉字符串左右兩側(cè)的空格,中間的干涉不了,用于檢測字符串是不是由任意個空格組成
Accepted代碼如下:
public int lengthOfLastWord(String s) { int num=0; int remember=0;//用來記住空格前面的那個字符,防止空格出現(xiàn)在最后 if(s.length()==0) { return 0; } else if (s.trim().isEmpty()) { return 0;//判斷整個字符串是否全部為空格組成 } else { for(int i=0;i<s.length();i++){ num++;//用來計數(shù),每次遇到空格則重新計數(shù) if(num!=1) { remember=num;} if(s.substring(i,i+1).equals(" ")){ num=0;//遇到空格置零即可 } } if(num==0){ return (remember-1); } else{return num;} } }
新聞熱點
疑難解答