14. Longest Common Prefix
Leetcode
https://leetcode.com/problems/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 "".
è§£ç”
方法一
var longestCommonPrefix = function(strs) {
let output = "";
let i = 0;
if (strs.length === 1) return strs[0];
while(true) {
let str = strs[0][i];
let j = 1;
while(j<strs.length && i<strs[0].length) {
if (str !== strs[j][i]) return output;
j++;
}
if(i>=strs[0].length) break;
output += str;
i++;
}
return output;
};Runtime: 88 ms, faster than 47.43% of JavaScript online submissions for Longest Common Prefix.
Memory Usage: 41 MB, less than 16.77% of JavaScript online submissions for Longest Common Prefix.
測資
let strs = ["flower","flow","flight"];
strs = ["dog","racecar","car"];
console.log(longestCommonPrefix(strs));Last updated
Was this helpful?