Problem
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
Input: strs = ["flower","flow","flight"]Output: "fl"
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 lower-case English letters.
Solution
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function (strs) {
if (strs.length === 1) {
return strs[0];
}
var commonStr = strs[0];
for (let i = 1; i < strs.length; i++) {
var lastIndex = commonStr.length;
for (let ii = 0; ii < commonStr.length && ii < strs[i].length; ii++) {
if (commonStr[ii] !== strs[i][ii]) {
lastIndex = ii;
break;
}
}
if (lastIndex >= strs[i].length) {
lastIndex = strs[i].length;
}
commonStr = commonStr.slice(0, lastIndex);
}
return commonStr;
};
