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.
題意是找出一個(gè)字符串最后一個(gè)單詞,字符串中每個(gè)單詞用空格隔開(kāi)。
這道題的坑:1、字符串中可能沒(méi)有空格;2、字符串中全是空格;3、字符串末尾或開(kāi)始是空格

1、自己做的時(shí)候沒(méi)有想到trim或者lastIndexOf這些方法,思路是兩個(gè)變量tmp和cnt,tmp記錄當(dāng)前單詞的長(zhǎng)度,cnt記錄最后一個(gè)單詞長(zhǎng)度。碰到的不是空格tmp++,如果是空格并且tmp大于0,則把cnt更新為tmp,tmp再置0。如果最后一個(gè)字符不是空格,需要再判斷一次tmp。

public int lengthOfLastWord1(String s) {
    if (s == null || s.length() == 0) {
        return 0;
    }

    int tmp = 0, res = 0;
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == ' ') {
            if (tmp > 0) {
                res = tmp;
            }
            tmp = 0;
        } else {
            tmp++;
        }
    }
    if (tmp != 0) {
        res = tmp;
    }

    return res;
}

2、應(yīng)用trim的方法,trim會(huì)把字符串前后的空格去掉,因此我們從最后一個(gè)字符向前找,遇到空格或者找到第一個(gè)字符停止,計(jì)數(shù)結(jié)果就是最后一個(gè)單詞長(zhǎng)度。

public int lengthOfLastWord2(String s) {
    if (s == null || s.length() == 0) {
        return 0;
    }

    s = s.trim();
    int cnt = 0;
    for (int i = s.length() - 1; i >= 0; i--) {
        if (sTrim.charAt(i) != ' ') {
            cnt++;
        } else {
            break;
        }
    }

    return cnt;
}

3、lastIndexOf方法可以直接找到最后一個(gè)空格的索引位置k,所以trim以后,用字符串長(zhǎng)度減去k再加1就是結(jié)果(lastIndexOf返回的索引從0開(kāi)始,所以需要再加1)。

public int lengthOfLastWord(String s) {
    s = s.trim();
    int lastIndex = s.lastIndexOf(' ') + 1;
    return s.length() - lastIndex;        
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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