我用JS刷LeetCode


最長公共前綴:

說明:現階段的解題暫未考慮複雜度問題

Question:

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

Note:

All given inputs are in lowercase letters a-z.

中文題目:

編寫一個函數來查找字符串數組中的最長公共前綴。

如果不存在公共前綴,返回空字符串 “”。

注意:

所有輸入只包含小寫字母 a-z 。

Example:

<code>
Input: ["flower","flow","flight"]
Output: "fl"
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
/<code>

個人分析:

  1. 「公共」,說明是數組中的每個元素所共有的,「前綴」,說明從元素的左邊開始算起。
  2. 先考慮特殊情況:當數組為空時,直接返回空字符串
  3. 看到題目稍加思索,應該想到:先比較數組中每個元素的第一位,如果都相同,則開始比較每個元素的第二位,依次類推;直到出現一個元素的某一位不在其他元素中都出現,此時返回這個元素之前的值
  4. 因為公共前綴是在在所有的元素中都存在的,所以我們可以以第一個元素作為標記點,將他的每一位和其他元素的每一位進行比較。
  5. 如果第一個元素遍歷完成還沒出現不在其他元素中值,則直接返回第一個元素。
  6. 得出如下答案。

Answer:

<code>var longestCommonPrefix = function (strs) {
if (strs.length === 0) return ''
let result = strs[0]
for (let j = 0; j < tag.length; j++) {
for (let i = 0; i < strs.length; i++) {
if (strs[i][j] !== result[j]) {
return strs[i].slice(0, j);
}
}
}
return result
};
/<code>

其他:

本題更多 JavaScript 解析,請看「瞭解更多」


分享到:


相關文章: