Leetcode - Length of Last Word

Question

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.


Example

Given s = “Hello World”,
return 5.


Java Code

public static int lengthOfLastWord(String s) {
    int r, l;

    //忽略字符串s尾部的若干空格,遇到非空格字符或者到達字符串頭則結束
    for(r = s.length() - 1; r >= 0 && s.charAt(r) == ' '; --r);

    //如果字符串s是個空串或只包含若干空格符,則不包含任何單詞
    if(r == -1) return 0;

    //統計最後一個單詞的長度,遇到空格或者到達字符串頭則結束
    for(l = r - 1; l >= 0 && s.charAt(l) != ' '; --l);

    //r和l分別指向最後一個單詞的尾和頭(或頭的前一位)
    return (r - l);
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章