[LeetCode][JavaScript]14. Longest Common Prefix

Athem
1 min readDec 20, 2019

--

這是陣列內的字串比對

題目在這邊:https://leetcode.com/problems/longest-common-prefix/

題目

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:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters a-z.

思考模式

  1. 先排除undefined跟空值。
  2. 用reduce()比對陣列前後元素的特性,搭配迴圈從index0開始比對。

解題筆記

心得

雖然我的leetcode幾乎都是直接讀別人的解法,讀到easy分類的時候真的滿有成就感的。

--

--