如何在Scala中找到两个字符串的最长公共前缀?

Mic*_*ael 11 string scala list-comprehension

如何在Scala中找到两个字符串的最长公共前缀?

我可能可以编写一个"命令式"解决方案(索引i在字符串上运行s(i) == t(i)),但我正在寻找一个"功能样式"解决方案(例如,不显式更新索引变量).

mis*_*tor 26

scala> "helloworld".zip("hellohell").takeWhile(Function.tupled(_ == _)).map(_._1).mkString
res130: String = hello
Run Code Online (Sandbox Code Playgroud)

  • 如果你将`"helloworld".zip("hellohell")改为`("helloworld","hellohell").zipped`,我认为这样可以解决效率低下问题. (7认同)

Lui*_*hys 6

另一个递归版本。

def pref(s: String, t: String, out: String = ""): String = {
  if (s == "" || t == "" || s(0) != t(0)) out
  else pref(s.substring(1), t.substring(1), out + s(0))
}
Run Code Online (Sandbox Code Playgroud)

它比 sjj 快 10 倍以上,是 missingfaktor 的两倍多。Java 的substring速度很快,因为它String是不可变的。