Javascript String Get longest Common Prefix

Description

Javascript String Get longest Common Prefix

/**//from  ww w  .ja va 2  s . co  m
 * @function longestCommonPrefix
 * @param {string[]} strings
 * @return {string}
 */

// find and return the longest common prefix ammong an array
// of strings. return null if no such common prefix exists.

// ex1: ['people', 'peeps', 'person', 'pendulum'] => 'pe'
// ex2: ['hello', 'hers', 'his', 'hint', 'hurts'] => 'h'
// ex3: ['goodbye', 'good', 'ok', 'great', 'bad'] => null

const longestCommonPrefix = (strings) => {
  var commonPrefix = "";
  var index = 0;

  var isMatch = true;
  
  while (isMatch) {
    var currChr = null;
    for (var s of strings) {
      if (index === s.length) {
        isMatch = false;
        break;
      } else {
        var c = s.charAt(index);
        if (currChr) {
          if (currChr !== c) {
            isMatch = false;
            break;
          }
        } else {
          currChr = c;
        }
      }
    }

    if (isMatch) {
      commonPrefix += currChr;
    }

    index++;
  }
  
  return commonPrefix;
}

console.log(longestCommonPrefix(['cooler', 'coolest', 'cool', 'cooling', 'cooled']));
console.log(longestCommonPrefix(['people', 'peeps', 'person', 'pendulum']));
console.log(longestCommonPrefix(['hello', 'hers', 'his', 'hint', 'hurts']));
console.log(longestCommonPrefix(['goodbye', 'good', 'ok', 'great', 'bad']));



PreviousNext

Related