LeetCode EP.7

14. Longest Common Prefix

Photo by Nicolene Olckers on Unsplash

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Example 2:

Constraints:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lowercase English letters.

思路

這題在Kotlin有兩種解法,第一種是直覺的使用兩種迴圈來解,先取出字串陣列的第一個元素。由後往前遞迴像如下圖,這裡的時間複雜度是n的平方,你可能會解出如下面Answer 1的解答,for loop會從1開始是因為我們已經取first element出來驗證了,就不需要再驗一次。

想不出來或是只寫的出現在這種高時間複雜度也沒關係,重點是理解這題的解答畢竟在面試當下,緊張不可能每次都寫出最佳解,解出來起碼還有個基本盤。

那也看到有人利用Kotlin提供另一個解法,使用commonPrefixWith 這個解法很棒也很優秀非常的乾淨,但不是每個語言都有這麼好用的function可以使用,且這個解答必須去理解reduce & commonPrefixWith

解答

Answer 1
Answer 2

那如果想玩玩看的話也可以參考我的 Github 使用 IntelliJ 就可以 Build 了,裡面也寫了 Test 來驗證。

--

--

陳建維 Ben
工程師求生指南(Sofware Engineer Survival Guide)

喜愛新鮮知識充滿好奇心的Mobile工程師,3C愛好者也是書蟲。連絡信箱:tttw216@gmail.com;目前遷移至我的Blog: https://awilab.com/