[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.

Example:

Input: "Hello World"
Output: 5

 

這道題難度不是很大。先對輸入字符串做預處理,去掉開頭和結尾的空格,然后用一個計數器來累計非空格的字符串的長度,遇到空格則將計數器清零,參見代碼如下:

 

解法一:

class Solution {
public:
    int lengthOfLastWord(string s) {
        int left = 0, right = (int)s.size() - 1, res = 0;
        while (s[left] == ' ') ++left;
        while (s[right] == ' ') --right;
        for (int i = left; i <= right; ++i) {
            if (s[i] == ' ') res = 0;
            else ++res;
        }
        return res;
    }
};

 

昨晚睡覺前又想到了一種解法,其實不用上面那么復雜的,這里關心的主要是非空格的字符,那么實際上在遍歷字符串的時候,如果遇到非空格的字符,只需要判斷其前面一個位置的字符是否為空格,如果是的話,那么當前肯定是一個新詞的開始,將計數器重置為1,如果不是的話,說明正在統計一個詞的長度,計數器自增1即可。但是需要注意的是,當 i=0 的時候,無法訪問前一個字符,所以這種情況要特別判斷一下,歸為計數器自增1那類,參見代碼如下:

 

解法二:

class Solution {
public:
    int lengthOfLastWord(string s) {
        int res = 0;
        for (int i = 0; i < s.size(); ++i) {
            if (s[i] != ' ') {
                if (i != 0 && s[i - 1] == ' ') res = 1;
                else ++res;
            }
        }
        return res;
    }
};

 

下面這種方法是第一種解法的優化版本,由於只關於最后一個單詞的長度,所以開頭有多少個空格起始並不需要在意,從字符串末尾開始,先將末尾的空格都去掉,然后開始找非空格的字符的長度即可,參見代碼如下:

 

解法三:

class Solution {
public:
    int lengthOfLastWord(string s) {
        int right = s.size() - 1, res = 0;
        while (right >= 0 && s[right] == ' ') --right;
        while (right >= 0 && s[right] != ' ' ) {
            --right; 
            ++res;
        }
        return res;
    }
};

 

這道題用Java來做可以一行搞定,請參見這個帖子.

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/58

 

參考資料:

https://leetcode.com/problems/length-of-last-word/

https://leetcode.com/problems/length-of-last-word/discuss/21927/My-3-line-0-ms-java-solution

https://leetcode.com/problems/length-of-last-word/discuss/21892/7-lines-4ms-C%2B%2B-Solution

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM