【发布时间】:2017-01-17 10:20:41
【问题描述】:
我正在完成App Academy's practice problems 的第一个编码挑战,并且对为#8 附近的 az 提供的解决方案有疑问:
# Write a method that takes a string in and returns true if the letter
# "z" appears within three letters **after** an "a". You may assume
# that the string contains only lowercase letters.
#
# Difficulty: medium.
def nearby_az(string)
idx1 = 0
while idx1 < string.length
if string[idx1] != "a"
idx1 += 1
next
end
idx2 = idx1 + 1
while (idx2 < string.length) && (idx2 <= idx1 + 3)
if string[idx2] == "z"
return true
end
idx2 += 1
end
idx1 += 1
end
return false
end
# These are tests to check that your code is working. After writing
# your solution, they should all print true.
puts("\nTests for #nearby_az")
puts("===============================================")
puts('nearby_az("baz") == true: ' + (nearby_az('baz') == true).to_s)
puts('nearby_az("abz") == true: ' + (nearby_az('abz') == true).to_s)
puts('nearby_az("abcz") == true: ' + (nearby_az('abcz') == true).to_s)
puts('nearby_az("a") == false: ' + (nearby_az('a') == false).to_s)
puts('nearby_az("z") == false: ' + (nearby_az('z') == false).to_s)
puts('nearby_az("za") == false: ' + (nearby_az('za') == false).to_s)
puts("===============================================")
在第二个while循环中:
while (idx2 < string.length) && (idx2 <= idx1 + 3)
为什么条件(idx2 < string.length) 是必要的?我在没有它的情况下测试了代码并得到了相同的结果。
感谢您的帮助。
【问题讨论】:
-
可以说,它是必需的,因为实现不是非常惯用的 Ruby。更惯用的方法可能是基于 string#split
标签: ruby while-loop conditional-statements