Question:
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: ["flower","flow","flight"]
Output: "fl"
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Solution:
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function(strs) {
const start = strs[0];
const result = [];
let vaild = function (index) {
for (let j = 1 ; j < strs.length; j++) {
if (strs[0].charAt(index) != strs[j].charAt(index)) {
return false;
}
}
return true;
}
for (let i in start) {
if (!vaild(i)) break;
result.push(start.charAt(i));
}
return result.join('');
};
Runtime: 60 ms, faster than 52.23% of JavaScript online submissions for Longest Common Prefix.