problem06-10
声明
该系列文章来自:http://aperiodic.net/phil/scala/s-99/
大部分内容和原文相同,加入了部分自己的代码。
如有侵权,请及时联系本人。本人将立即删除相关内容。
P06 (*) Find out whether a list is a palindrome.
要求
判断一个list是不是回文
Example:
|
|
方案
- (1) 反转list之后和自身反转之前的元素顺序一致
|
|
P07 (**) Flatten a nested list structure.
要求
将一个内嵌N重list的list所有元素提取至一个新的list,新的list不能嵌套list结构
Example:
|
|
方案
- (1) 递归+List.flatMap
|
|
P08 (**) Eliminate consecutive duplicates of list elements.
要求
If a list contains repeated elements they should be replaced with a single copy of the element. The order of the elements should not be changed.
Example:
|
|
方案
- (1) List.dropWhile + recursive
|
|
- (2) List.dropWhile + tail-recursive
|
|
- (3) List.dropWhile + tail-recursive
|
|
- (4) foldRight
|
|
P09 (**) Pack consecutive duplicates of list elements into sublists.
要求
If a list contains repeated elements they should be placed in separate sublists.
Example:
|
|
方案
- (1) span + 普通递归
|
|
- (2) span + 尾递归
|
|
P10 (*) Run-length encoding of a list.
要求
Use the result of problem P09 to implement the so-called run-length encoding data compression method. Consecutive duplicates of elements are encoded as tuples (N, E) where N is the number of duplicates of the element E.
Example:
|
|
方案
- (1) map
|
|