gpt4 book ai didi

ruby - 删除相邻的重复子串

转载 作者:数据小太阳 更新时间:2023-10-29 07:51:37 24 4
gpt4 key购买 nike

我正在尝试删除 k 长度的重复相邻子字符串,其中 k 指的是字数。代码应该以递归方式工作,从

开始

k = 1 个单词取决于k = 字符串中的单词数

例如,

i sat down to write an article an article this morning but found that i i could make no progress

成为

i sat down to write an article this morning but found that i could make no progress

我如何实现这一点?我可以通过以下方式实现 1 长度的相邻子字符串删除:

str.chunk{|n| n}.map(&:first)

最佳答案

s = "i sat down to write an article an article this morning but found that i i could make no progress"

max = s.scan(/\S+/).length
# => 20
1.upto(max).each_with_object(s) do
|n, s| s.gsub!(/((?:\b\s*\S+){#{n}})\1/, '\1')
end
# => "i sat down to write an article this morning but found that i could make no progress"

顺便说一下,

"I like to move it move it, I like to move it move it"

将导致:

"I like to move it, I like to move it"

不是:

"I like to move it"

正如你在评论中提到的,因为没有相邻的重复超出上面的字符串(注意逗号和空格)。

关于ruby - 删除相邻的重复子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52779207/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com