LeetCode 算法题【Easy】:14. Longest Common Prefix

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

Example 1:

1
2
3
Input: strs = ["flower","flow","flight"]
Output: "fl"

Example 2:

1
2
3
4
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Constraints:

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

My Answer

1
2
3
4
5
6
7
8
9
10
11
12
var longestCommonPrefix = function(strs) {
let result = ''
for (let i = 0; i <= strs[0].length; i ++) {
const s = strs[0].slice(0, i + 1)
if (strs.every(str => str.startsWith(s))) {
result = s
} else {
break
}
}
return result
};

My Answer’s Performance

4