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.

大意:

給出一個由大小寫字母和空格組成的字符串s,返回其最后一個單詞的長度。
如果最后一個單詞不存在,返回0。
注意:單詞是指僅有非空格字符組成的序列。
例子:
給出 s = "Hello World",
返回 5。

思路:

題目并不難,只是要注意,我在用測試用例嘗試的時候發(fā)現(xiàn),如果給出的字符串最后是空格,也會取空格前最后一個單詞的長度,也就是說即使最后是多個空格,只要前面還有單詞,就將其視為最后一個單詞。

我的做法是遍歷數(shù)組,遇到字符串第一個就是字母或者說字母前一個字符是空格時,就將其視為一個單詞的開始,令結(jié)果回到1,重新計算長度,其余遇到字母就將結(jié)果加一,遇到空格就不管了。

代碼(Java):

public class Solution {
    public int lengthOfLastWord(String s) {
        int length = 0;
        char[] arr = s.toCharArray();
        for (int i = 0; i < arr.length; i++) {
            if (i == 0) {
                if (arr[i] != ' ') length ++;
            } 
            else if (arr[i-1] == ' ' && arr[i] != ' ') length = 1;
            else if (arr[i] != ' ') length ++;
        }
        return length;
    }
}

他山之石:

public class Solution {
    public int lengthOfLastWord(String s) {
        int len = s.length();
        int i = len -1;
        int empty = 0;
        if(s == null || len == 0)
            return 0;
        while(i>=0 && s.charAt(i)==' '){
            i--;
            empty++;
        }
        while(i>=0 && s.charAt(i)!=' ')
            i--;
        return len- empty - (i+1);
    }
}

這個做法是從后往前遍歷字符串,末尾如果有空格,先把空格去除干凈,然后取字母的長度,再次遇到空格打止,因為是從后往前遍歷,不需要全部遍歷完整個字符串,所以會快一點。

合集:https://github.com/Cloudox/LeetCode-Record


查看作者首頁

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容