我正在完成 App Academy's practice problems对于第一个编码挑战,并对为 #8 nearby 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)
必要的?我在没有它的情况下测试了代码并得到了相同的结果。
感谢您的协助。
why is the condition (idx2 < string.length
) necessary?
这不是必需的。当 idx2 超出字符串的边界时,它可以防止循环的无意义迭代。
寻址超出字符串长度的字符将返回 nil。 nil
永远不会等于 'z'
.所以我们不妨在到达终点时就停下来。这就是检查的目的,优化。
在其他情况下,越界访问通常是一种严重的违规行为,会导致各种问题(通常是崩溃)。因此,始终这样做是有意义的。
我是一名优秀的程序员,十分优秀!