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
.
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function(strs) {
if (!strs.length) {
return '';
}
const len = strs[0].length;
let i = 0;
for (; i < len; i++) {
if (!isSame(strs, i)) {
break;
};
}
return strs[0].substring(0, i);
function isSame(strs, idx) {
for (let j = 0; j < strs.length - 1; j++) {
if (strs[j][idx] !== strs[j + 1][idx]) {
return false;
}
}
return true;
}
};
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function(strs) {
if (!strs.length) {
return '';
}
if (strs.length === 1) {
return strs[0];
}
let minWord = strs[0];
for (let n = 1; n < strs.length; n++) {
if (strs[n].length > minWord.length) {
minWord = strs[n];
}
}
const len = minWord.length;
let i = 0;
for (; i < len; i++) {
if (!isSame(strs, i)) {
break;
};
}
return minWord.substring(0, i);
function isSame(strs, idx) {
for (let j = 0; j < strs.length - 1; j++) {
if (strs[j][idx] !== strs[j + 1][idx]) {
return false;
}
}
return true;
}
};