gpt4 book ai didi

ruby - 如何通过Ruby查找字符串中出现的次数

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

<分区>

我是 Ruby 的新手,通过 solving IOI questions 学习它.

示例输入文件的第一行是“O”的数字。如果它是 1 那么它需要找到 'IOI',如果它是 2,那么它需要找到 'IOIOI' 等等。

第二个数字 13 表示第三行中的字符数。问题是找到“IOI”出现的次数。

下面的示例应该给出 4。

我做了一个方法并在 while 循环中使用 if 语句。但它给出了一个错误 ioioi.rb:14: syntax error, unexpected keyword_end (SyntaxError)。我在 while 循环中尝试的是查找前 3 个字符是否相等,以及是否将 count 增加一个。并删除第一个字符并重复该过程。

示例输入文件

1
13
OOIOIOIOIIOII

输出应该是

4

我的类(class)Ioioi

def self.frequency(file_name)
file = File.new(file_name, 'r').each_line.map(&:strip)
count = 0
o_str = file.shift # '1'
o_num = o_str.to_i
findme = "IO" * o_num + "I"
length = file.shift # '13'
input = file.join
while file.size > 0 do
if file[0..(2*o_num)].eql?(findme)
count +=
end
file = file[1..-1] # delete the first letter
end
count
end

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