LeetCode 58. Length of Last Word

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.

題意,找到,最后一個' '后面的單詞,求出它的長度,如果沒有,就返回0。

思路:從后向前遍歷,發現是字母了,觸發標識位,如果還是字母繼續,發現' '直接停止,返回剛才的單詞的長度。

java代碼:

public int lengthOfLastWord(String s) { 
        if(s==null || s.length() == 0)
            return 0;
     
        int result = 0;
        int len = s.length();
     
        boolean flag = false;
        for(int i=len-1; i>=0; i--){
            char c = s.charAt(i);
            if((c>='a' && c<='z') || (c>='A' && c<='Z')){
                flag = true;
                result++;
            }else{
                if(flag)
                    return result;
            }
        }
     
        return result;
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容