觀前提醒:
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.
可參考以下的圖,簡單來說,類似"削足適履"的概念。英文版可參考右邊連結LeetCode Solution
/**
* @param {string[]} strs
* @return {string}
*/
// 解題心法:參力扣解法一
// https://leetcode.com/problems/longest-common-prefix/solution/
var longestCommonPrefix = function (strs) {
// 處理edge case
if (strs.length === 0) return "";
let ansPrefix = strs[0];
for (let i = 0; i < strs.length; i++) {
while (strs[i].indexOf(ansPrefix) !== 0) {
ansPrefix = ansPrefix.substring(0, ansPrefix.length - 1);
if (ansPrefix === null) return "";
}
}
return ansPrefix;
};
這題的解法,我是自己 TRY 一陣子後,總覺得好像還是差了一點,
便默默地跑去看了人家官方的 Guideline。
謝謝大家的收看,LeetCode 小學堂我們下次見~