gpt4 book ai didi

ruby - 在 Ruby 中压缩双字符

转载 作者:太空宇宙 更新时间:2023-11-03 17:25:03 25 4
gpt4 key购买 nike

压缩字符串中多字符的最佳方法是什么?

Example:
hahahahahaha => ha
lalalala => la
awdawdawdawd => awd

str.squeeze("ha") # doesn't work
str.tr("haha", "ha") # doesn't work

最佳答案

def squeeze(s)
s.gsub(/(.+?)\1+/, '\1')
end

puts squeeze('hahahaha') # => 'ha'
puts squeeze('awdawdawd') # => 'awd'
puts squeeze('hahahaha something else') # => 'ha something else'

关于ruby - 在 Ruby 中压缩双字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14498136/

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