Javascript Array Find the longest Common Prefix

Description

Javascript Array Find the longest Common Prefix

/**//from  www .ja  va  2  s . c  o  m
 * @param {string} str1
 * @param {string} str2
 * @return {string}
 */
var findCommonPrefix = function(str1, str2) {
  var result = '';

  for (var i = 0, j = 0; i < str1.length && j < str2.length; i++, j++) {
    if (str1[i] != str2[j]) {
      break ;
    }
    result += str1[i];
  }
  return result;
};

/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
  var prefix = strs.length ? strs[0] : "";

  for (var i = 1; i < strs.length; i++) {
    prefix = findCommonPrefix(prefix, strs[i]);
  }
  return prefix;
};

console.log(longestCommonPrefix(['abcde11111', 'abcd111', 'abcd11111', 'abcdefg11111']));



PreviousNext

Related