dimanche 8 août 2021

Longest Common Prefix in Javascript

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 lower-case English letters.

My solution:

let strs = ["flower", "flow", "flight"];

var longestCommonPrefix = function (strs) {
  for (let i = 0; i < strs.length; i++) {
    for (let j = 0; j < strs[i].length; j++) {
       // console.log(strs[i+2][j]);
      if (strs[i][j] == strs[i + 1][j] && strs[i + 1][j] ==strs[i + 2][j]) {
        return (strs[i][j]);
        
      } else {
        return "0";
      }
    }
  }
};

console.log(longestCommonPrefix(strs));

Output: f

How can I iterate over every character and check if it is same and then go for next and if it fails then the longest common prefix will be returned?

Aucun commentaire:

Enregistrer un commentaire