How can I print out all possible letter combinations a given phone number can represent?

前端 未结 30 2205
逝去的感伤
逝去的感伤 2020-12-22 18:01

I just tried for my first programming interview and one of the questions was to write a program that given a 7 digit telephone number, could print all possible combinations

30条回答
  •  执念已碎
    2020-12-22 18:36

    I tried it in ruby, and came up with a different way of doing, it's probably not efficient, like time and space O(?) at this point, but I like it because it uses Ruby's builtin Array.product method. What do you think?

    EDIT: I see a very similar solution in Python above, but I hadn't seen it when I added my answer

    def phone_to_abc(phone)
    
      phone_abc = [
        '0', '1', 'abc', 'def', 'ghi',
        'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'
      ]
    
      phone_map = phone.chars.map { |x| phone_abc[x.to_i].chars }
      result = phone_map[0]
      for i in 1..phone_map.size-1
        result = result.product(phone_map[i])
      end
      result.each { |x|
        puts "#{x.join}"
      }
    
    end
    
    phone_to_abc('86352')
    

提交回复
热议问题