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 1:
Input: strs = ["flower","flow","flight"] Output: "fl"
Example 2:
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 lowercase English letters.
Solution
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function(strs) {
let output = "";
let smallestlength = strs[0].length;
for(let i = 0; i < strs.length;i++){
if(strs[i] < smallestlength)
{
smallestlength = strs[i].length;
}
}
for(let j = 0; j < smallestlength; j++){
let pass = true;
let prefix = strs[0][j];
for(let i = 0; i < strs.length;i++){
if(prefix != strs[i][j])
{
pass = false;
}
}
if(pass){
output = output+prefix;
}
else{
break;
}
}
return output;
};
A freelance web developer with a decade of experience in creating high-quality, scalable web solutions. His expertise spans PHP, WordPress, Node.js, MySQL, MongoDB, and e-commerce development, ensuring a versatile approach to each project. Aadi’s commitment to client satisfaction is evident in his track record of over 200 successful projects, marked by innovation, efficiency, and a customer-centric philosophy.
As a professional who values collaboration and open communication, Aadi has built a reputation for delivering projects that exceed expectations while adhering to time and budget constraints. His proactive and problem-solving mindset makes him an ideal partner for anyone looking to navigate the digital landscape with a reliable and skilled developer.