鱼儿慢慢游~~

导航

 

题目描述:

Decode a run-length encoded list.
Given a run-length code list generated as specified in problem P10, construct its uncompressed version.
Example:

scala> decode(List((4, 'a), (1, 'b), (2, 'c), (2, 'a), (1, 'd), (4, 'e)))
res0: List[Symbol] = List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)

根据List中的元素,将其展开, 与之前的encodeList 做相反的操作。 

思路: 使用之前提到的foldLeft函数, 从左到右遍历List,将其每一个元组展开,放入初始值里面。

代码:

   def decodeList[T](a:List[(Int, T)]): List[T] = a.foldLeft(List[T]()){
      case (res, cur) => {
           val count = cur._1
           val content = cur._2
           res:::List.fill(count)(content)
       }
      }
    val b = List((10, "a"), (2,"zb"))
    println(decodeList(b))

List.fill:

  def fill[A](n: Int)(elem: => A): CC[A] = {
    val b = newBuilder[A]
    b.sizeHint(n)
    var i = 0
    while (i < n) {
      b += elem
      i += 1
    }
    b.result
  }

向集合中插入n个类型为A的元素。

posted on 2016-11-08 15:20  miss_UU  阅读(3101)  评论(0编辑  收藏  举报