一 问题描述
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
翻译:
从一个字符串数组中挑出前几个共有的字符。如果没有任何一个字符共有,就返回空字符串。输入的字符串数组的字符保证是a-z之间的小写字母。
二 解法
1. 第一解法(个人)
思路:
用两个for循环,依次检查。为了减少for循环中判断特殊情况的难度,在程序开始时,将空数组,和只有一个空字符串元素的数组,和只有一个非空字符串元素的数组这三种情况排除掉。
代码:
var longestCommonPrefix = function(strs) {
let s = '';
if (!strs.length || !strs[0].length)
return "";
if (strs.length === 1)
return strs[0];
for (let i = 0; i < strs[0].length; i++) {
for (let j = 1; j < strs.length; j++) {
if (strs[j][i] && strs[0][i] === strs[j][i]) {
console.log("for for if: ", strs[j][i]);
continue;
}
console.log("for for: ", s)
return s;
}
s += strs[0][i];
console.log("for: ", s);
}
return s;
};
结果:
Runtime: 52 ms, faster than 94.58% of JavaScript online submissions for Longest Common Prefix.
Memory Usage: 35.1 MB, less than 51.52% of JavaScript online submissions for Longest Common Prefix.
2. 第二解法(个人,优化)
思路:
-
- 用sort排序
-
- 此时,不需要将所有的元素全部检查,只需要检查首尾两个元素,因为sort按字典序排序,因此,首尾元素的字符差异最大。
如果首尾一致,中间必一致。
代码:
var longestCommonPrefix2 = function(strs) {
if (!strs.length || !strs[0].length)
return "";
if (strs.length === 1)
return strs[0];
strs.sort();
let len = strs.length - 1;
let i = 0;
while (strs[0][i] && strs[len][i] && strs[0][i] === strs[len][i])
i++;
return strs[0].substring(0, i);
};
结果:
Runtime: 52 ms, faster than 94.58% of JavaScript online submissions for Longest Common Prefix.
Memory Usage: 33.7 MB, less than 97.90% of JavaScript online submissions for Longest Common Prefix.
By DoubleJan
2019.9.9