这不是作业,只是我在网上发现的一个看起来很有趣的面试问题。
所以我首先看了一下:电话用语问题——但它似乎措辞不当/引起了一些争议。我的问题几乎相同,除了我的问题更多是关于它背后的时间复杂度。
当给定一个 10 位数的电话号码作为输入时,您希望列出所有可能的单词。所以这就是我所做的:`
def main(telephone_string)
hsh = {1 => "1", 2 => ["a","b","c"], 3 => ["d","e","f"], 4 => ["g","h","i"],
5 => ["j","k","l"], 6 => ["m","n","o"], 7 => ["p","q","r","s"],
8 => ["t","u","v"], 9 => ["w","x","y","z"], 0 => "0" }
telephone_array = telephone_string.split("-")
three_number_string = telephone_array[1]
four_number_string = telephone_array[2]
string = ""
result_array = []
hsh[three_number_string[0].to_i].each do |letter|
hsh[three_number_string[1].to_i].each do |second_letter|
string = letter + second_letter
hsh[three_number_string[2].to_i].each do |third_letter|
new_string = string + third_letter
result_array << new_string
end
end
end
second_string = ""
second_result = []
hsh[four_number_string[0].to_i].each do |letter|
hsh[four_number_string[1].to_i].each do |second_letter|
second_string = letter + second_letter
hsh[four_number_string[2].to_i].each do |third_letter|
new_string = second_string + third_letter
hsh[four_number_string[3].to_i].each do |fourth_letter|
last_string = new_string + fourth_letter
second_result << last_string
end
end
end
end
puts result_array.inspect
puts second_result.inspect
end
首先,这是我在几分钟内完成的,没有进行任何重构。所以我为混乱的代码道歉,我刚开始学习 Ruby 6 周前,所以请多多包涵!
所以最后我的问题是:我想知道这种方法的时间复杂度是多少。我的猜测是它会是 O(n^4) 因为第二个循环(对于四个字母的单词)嵌套了四次。虽然我不是很积极。所以我想知道这是否正确,以及是否有更好的方法来解决这个问题。