String 如何递归地找到字符串序列的公共根?
我希望能够读取字符串序列并返回字符串的公共词干。例如,如果我有以下序列:String 如何递归地找到字符串序列的公共根?,string,scala,recursion,sequences,String,Scala,Recursion,Sequences,我希望能够读取字符串序列并返回字符串的公共词干。例如,如果我有以下序列: val testSeq: Seq[String] = Seq("RootA_", "RootB_", "RootC_") 然后只返回字符串“Root” 我当前的函数看起来是这样的,但使用intersect意味着不需要的“\u”将作为根的一部分返回,即“根”。我尝试使用takeWhile,但没有成功 def findRoot(ss: Seq[String], root: String): String = ss match
val testSeq: Seq[String] = Seq("RootA_", "RootB_", "RootC_")
然后只返回字符串“Root”
我当前的函数看起来是这样的,但使用intersect意味着不需要的“\u
”将作为根的一部分返回,即“根”。我尝试使用takeWhile,但没有成功
def findRoot(ss: Seq[String], root: String): String = ss match {
case h :: Nil => h.intersect(root)
case h :: t => findRoot(t, h.intersect(t.head))
}
如果有一个内置的Scala方法,请告诉我!否则,如果有人想尝试解决这个问题,我们将不胜感激 据我所知,没有scala stdlib函数返回两个字符串的公共前缀 您可以使用
zip
和takeWhile
def findRoot(seq: Seq[String]): String = {
def prefix(a: String, b: String) = a
.zip(b)
.takeWhile { case (a, b) => a == b }
.map(_._1)
.mkString
@tailrec
def find(ss: Seq[String], root: String): String = ss match {
case h :: Nil => prefix(h, root)
case h :: t => find(t, prefix(h, root))
}
find(seq.tail, seq.head)
}
据我所知,没有scala stdlib函数返回两个字符串的公共前缀 您可以使用
zip
和takeWhile
def findRoot(seq: Seq[String]): String = {
def prefix(a: String, b: String) = a
.zip(b)
.takeWhile { case (a, b) => a == b }
.map(_._1)
.mkString
@tailrec
def find(ss: Seq[String], root: String): String = ss match {
case h :: Nil => prefix(h, root)
case h :: t => find(t, prefix(h, root))
}
find(seq.tail, seq.head)
}