更清洁的解决方案:
def pack[T](input: List[T]): List[List[T]] =
input.foldRight(Nil : List[List[T]]) ((e, accu) => accu match {
case Nil => List(List(e))
case curList@(h :: t) if e == h => List(e) :: curList
case curList@(h :: t) => List(List(e)) ::: curList
})
不使用任何库函数(丑陋):
def pack[T](input: List[T]): List[List[T]] = {
def packWithPrevious(remaining: List[T])(previous: List[T]): List[List[T]] =
remaining match {
case List() => List(previous)
case head :: tail =>
val nextIter = packWithPrevious(tail)(_)
previous match {
case List() => nextIter(List(head))
case prevHead :: _ =>
if (head != prevHead)
previous :: nextIter(List(head))
else
nextIter(head :: previous)
}
}
packWithPrevious(input)(List())
}
scala> val s = List('A', 'B', 'B', 'B', 'B', 'G', 'G', 'S', 'S', 'S', 'B', 'A', 'G')
s: List[Char] = List(A, B, B, B, B, G, G, S, S, S, B, A, G)
scala> pack(s)
res2: List[List[Char]] = List(List(A), List(B, B, B, B), List(G, G), List(S, S, S), List(B), List(A), List(G))
来源:https://github.com/izmailoff/scala-s-99/blob/master/src/main/scala/s99/p09/P09.scala
测试:https://github.com/izmailoff/scala-s-99/blob/master/src/test/scala/s99/p09/P09Suite.scala