Given a stringsconsists 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,Givens="Hello World",return5.
這道題個人覺得很簡單的哈。
重點就是要想一個辦法來判定這是不是最后一個word,什么時候最后一個word結束。
因為我們重點是最后一個word,所以寫loop的時候就從后頭往前。那么最簡單判定一個單詞是否結束的方法就是,判斷這個字母的下一個字符依舊是字母還是是別的什么符號,如果不是字母,那就表示這個單詞已經寫完啦。
但是要注意就是有一個比較特殊的情況。如果從后面先是從空格開始然后才是單詞呢。所以針對這個要額外多寫一個if statement哈。
另外就是注意字母區分大小寫的哈。
所以想通了這個,就很好寫了。
public class Solution { public int lengthOfLastWord(String s) { //specail case if(s==null){ return 0; } int count=0; for(int i=s.length()-1;i>=0;i--){ char c=s.charAt(i); if((c>='a'&&c<='z')||(c>='A'&&c<='Z')){ count++; }else{ if(count==0){ count=0; }else{ return count; } } } return count; }}新聞熱點
疑難解答