任何人都可以解释一下这段代码吗?我不明白具体:
elsif idx2 > idx1
is_repeat = true
end
完整代码如下所示:
# Write a method that takes in a string and returns the number of
# letters that appear more than once in the string. You may assume
# the string contains only lowercase letters. Count the number of
# letters that repeat, not the number of times they repeat in the
# string.
#
# Difficulty: hard.
def num_repeats(array)
repeats = 0
idx1 = 0
while idx1 < array.length
is_repeat = false
idx2 = 0
while idx2 < array.length
if array[idx1] != array[idx2]
idx2 += 1
next
elsif idx2 < idx1
# will have previously counted this repeat
break
elsif idx2 > idx1
is_repeat = true
end
idx2 += 1
end
if is_repeat
repeats += 1
end
idx1 += 1
end
return repeats
end
答案 0 :(得分:1)
如果之前的条件(if idx2 < array.length
和elsif idx2 < idx1
)都是false
但idx2 > idx1
是true
,那么将局部变量is_repeat
设置为true
...