LeetCode #58 Length of Last Word 解題思路及翻譯

LeetCode題目翻譯

英文原文如下

Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string.

A word is a maximal substring consisting of non-space characters only.

中文翻譯

給予一個由幾個單字且有幾個空白組成的字串 s,回傳最後一個單字的長度

一個單字的定義是其中只有不含空白之字元

LeetCode #58 Constraints

s的長度會介於1到104之間

s 只會包含英文字元跟空白字元

s 至少會包含一個單字 ➔ 不用考慮s整個為空字串的情況

接著來看看以下的範例

LeetCode #58 Example Pictures

先看範例1

各位應該一眼就能看到最熟悉的兩個單字吧,分別是「Hello」跟「World」這兩個單字吧

故回傳最後的單字「World」的長度 ➔ 5

再來看看範例2

最後一個單字是moon(後面的也是空白故不算)

故回傳最後的單字「moon」的長度 ➔ 4


解題思路

C# 解決方案

方案1 – 簡單的遞迴

public class Solution {
    public int LengthOfLastWord(string s) {
        
        int cnt = 0;
        
        for(int i = s.Length-1;i>=0;i--)
        {
            if(Char.IsWhiteSpace(s[i]))
            {
                if(cnt>0)
                {
                    return cnt;    
                }
                continue;
            }
            
            cnt+=1;
        }
        return cnt;
    }
}

最直覺的方式,因為要找最後一個單字的長度,所以從string的最後往前找

方案2 – String 底下的 Split

public class Solution {
    public int LengthOfLastWord(string s) {
        
        string[] tmp = s.Split(' ');          //使用Split對字串做空白切割
        string tmpStr;
        
        for(int i = tmp.Length-1; i>=0; i--)  //因為要最後的單字,故從陣列最後一位開始找
        {
            tmpStr = tmp[i];
            if(!String.IsNullOrEmpty(tmpStr)) //不是空的話
            {
                return tmpStr.Length;
            }
        }
        return 0;                             //應該不會跑到,題目有保證至少有一個單字
    }
}

大家可以看到上面的第三個註解那裡的程式 (空白那個),其實最早寫的時候是沒有的

但實際跑過之後發現,要是最後單字後面有一個或以上的空白,就會導致Array的最後出現空白字元

故還需加上判斷是否為Null或空白(String.IsNullOrEmpty)

方案2.1

已經知道單純的Split有空白的問題,那能不能找到其他辦法解決呢?

當然有! 大家看看上面那一句「最後單字後面有一個或以上的空白」

那我們對症下藥,就先對單字做個預先的處理

這時候我們就會找到內建的String.Trim( ) 這個方法,其中又分為以下3種

  • Trim( )
  • TrimEnd( )
  • TrimStart( )

Trim這個字在英文的意思就是 「修剪」

故方法即為針對字串進行特定字元(若無設定即對象為空白)的修剪

TrimStart 就是對字串的開頭 、TrimEnd 則是對字串的結尾 、Trim則是兩者都做

那現在把它實際運用在剛剛的程式碼中

public class Solution {
    public int LengthOfLastWord(string s) {
        s = s.TrimEnd();                 //Trim也可以,因為這裡只要對結尾做處理即可
        string[] tmp = s.Split(' ');
        return tmp[tmp.Length-1].Length; 
    }
}

是不是比剛剛簡單了許多,連迴圈都不用了

而一切就都只是多了一個小小的前置動作而已

方案2.2

什麼! 這樣你們也不滿意!! 不想對字串先處理??? (比案子遇上的客戶還麻煩餒…)

這時候我們要來看下官方對於Split的文件

疑?

Split 後面有一個 StringSplitOptions 參數可以帶入的

而其中的「RemoveEmptyEntries」 可以直接省略結果包含空字串的陣列元素

這..這不就我們要的嗎!

事不宜遲,趕緊來改看看

public class Solution {
    public int LengthOfLastWord(string s) {
        string[] tmp = s.Split(' ',StringSplitOptions.RemoveEmptyEntries);
        return tmp[tmp.Length-1].Length;
    }
}

Java解決方案

方案1

class Solution {
    public int lengthOfLastWord(String s) {
        int cnt = 0;
        
        for(int i = s.length()-1;i>=0;i--)
        {
            if(s.charAt(i)==' ')
            {
                if(cnt>0)
                {
                    return cnt;    
                }
                continue;
            }
            
            cnt+=1;
        }
        return cnt;
    }
}

方案2

class Solution {
    public int lengthOfLastWord(String s) {
        s = s.trim();
        String[] arr =  s.split("\\s+");
        
        return arr[arr.length-1].length();
    }
}

Python3 解決方案

方案1

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        cnt = 0;
        for i in range(len(s)-1,-1,-1):
            if(s[i]== ' '):
                if cnt>0 :
                    return cnt
                continue
            cnt+=1;
        return cnt

方案2

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        s = s.rstrip()  #or strip
        return len(s.split()[-1])

JavaScript 解決方案

方案1

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLastWord = function(s) {
    var cnt = 0;

    for(var i = s.length-1;i>=0;i--)
    {
        if(s[i]==' ')
        {
            if(cnt>0)
            {
                return cnt;    
            }
            continue;
        }

        cnt+=1;
    }
    return cnt;
};

方案2

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLastWord = function(s) {
    s = s.trim();
    var arr = s.split(' ');
    return arr[arr.length-1].length;
};

結論

看完這題各種不同的解法,大家可以看到善用內建的方法會有多少程式碼的差異

而這就是程式之所以讓人著迷的魅力啊

"Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live"

題目連結 : Length of Last Word – LeetCode

🧡如果這篇文章有幫上你的一點點忙,那是我的榮幸

🧡可以的話,幫我的FaceBook 粉絲專頁按個讚,我會很感謝的

✅如有任何疑問,歡迎透過留言或messenger讓我知道 !

最新文章

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *