Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

def longestCommonPrefix(strs: Array[String]):String = {
  if (strs.length == 0) ""
  else {
    strs.reduceRight((s1,s2) => {
      val l = s1.length min s2.length
      var i = 0
      while (i < l && s1(i) == s2(i)) {
        i += 1
      }
      s1.take(i)
    })
  }
}

longestCommonPrefix(Array())
longestCommonPrefix(Array("a"))
longestCommonPrefix(Array("abc","abcdef","abpoiuyt"))

Last updated