Write a function to find the longest common prefix in an array of strings.
If there is no common prefix, the empty string ""
.
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix for the input.
Problem-solving ideas
The first solution is to compare one by one, first compare the longest common prefix of the first and second strings, then use this prefix to compare with the third string, and so on.
function longestCommonPrefix(strs) {
return strs.reduce((accu, cur) => {
let prefix = "";
for (let i = 0; i < accu.length; i++) {
if (accu[i] === cur[i]) {
prefix += accu[i];
} else {
return prefix;
}
}
return prefix;
})
}
If you usereduce
if you do not specify the initial value, you must ensure that the array is not empty. Since this question has explained that thestrs
is greater than or equal to 1, there is no need to deal with empty values
Time complexity:O(s)
,s
is the sum of the number of characters in all strings
Space complexity:O(1)
The above method is easy to think of, but a lot of traversal operations are required, and the time complexity is high. The second method is to compare only the longest common prefix of the largest and smallest strings. The largest and smallest mentioned here refer to the order of ACSII encoding, for example, ab
less than abc
, abc
less than abcd
, and abcd
less than ac
. Then abc
and ab
and maximum ac
must be the common prefix of abcd
.
function longestCommonPrefix(strs) {
let min = 0, max = 0;
for (let i=0; i<strs.length; i++) {
if (strs[min] > strs[i]) {
// 记录最小字符串下标
min = i;
}
if (strs[max] < strs[i]) {
// 记录最大字符串下标
max = i;
}
}
for (let i=0; i<strs[min].length; i++) {
if (strs[min].charAt(i) !== strs[max].charAt(i)) {
return strs[min].substring(0, i);
}
}
return strs[min];
}
Time complexity:O(n+m)
,n
is the length of the array,m
is the length of the shortest character string array
Space complexity:O(1)
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。