【发布时间】:2015-09-30 10:23:04
【问题描述】:
给定字符串:
"See Spot Run"
我需要返回一个数组:
[ "See", "Spot", "run", "See Spot", "Spot run", "See Spot Run" ]
到目前为止,我有:
term = "The cat sat on the mat"
#=> "The cat sat on the mat"
arr = term.split(" ")
#=> ["The", "cat", "sat", "on", "the", "mat"]
arr.length.times.map { |i| (arr.length - i).times.map { |j| arr[j..j+i].join(" ") } }.flatten(1)
#=> ["The", "cat", "sat", "on", "the", "mat", "The cat", "cat sat", "sat on", "on the", "the mat", "The cat sat", "cat sat on", "sat on the", "on the mat", "The cat sat on", "cat sat on the", "sat on the mat", "The cat sat on the", "cat sat on the mat", "The cat sat on the mat"]
这种情况会发生很多次,所以你能想出一种方法让它更有效率吗?
【问题讨论】: