编写一个接受字符串的方法,并返回在字符串中出现多次的字母数。您可以假设该字符串仅包含小写字母。计算重复的字母数,而不是它们在字符串中重复的次数。
我将方法和测试用例实现为:
def num_repeats(string)
count = 0
dix = 0
new = ""
while dix < string.length
letter = string[dix]
if !(new.include?(letter))
new = new + "letter"
else
break
end
dix2 = dix + 1
while dix2 < string.length
if letter == string[dix2]
count +=1
break
end
dix2 +=1
end
dix += 1
end
puts(count.to_s)
return count
end
# These are tests to check that your code is working. After writing
# your solution, they should all print true.
puts('num_repeats("abdbc") == 1: ' + (num_repeats('abdbc') == 1).to_s)
# one character is repeated
puts('num_repeats("aaa") == 1: ' + (num_repeats('aaa') == 1).to_s)
puts('num_repeats("abab") == 2: ' + (num_repeats('abab') == 2).to_s)
puts('num_repeats("cadac") == 2: ' + (num_repeats('cadac') == 2).to_s)
puts('num_repeats("abcde") == 0: ' + (num_repeats('abcde') == 0).to_s)
测试结果:
1
num_repeats("abdbc") == 1: true
2
num_repeats("aaa") == 1: false
2
num_repeats("abab") == 2: true
2
num_repeats("cadac") == 2: true
0
num_repeats("abcde") == 0: true
对于返回false的第二个测试,我的代码有什么问题?
答案 0 :(得分:4)
您要将第{8}行"letter"
而不是letter
变量附加到new
。
if !(new.include?(letter))
new = new + "letter"
else
#...
end
变为:
unless new.include?(letter)
new = new + letter
else
#...
end