Leetcode: letter combinations for phone numbers

Source: Internet
Author: User

@author: Zzq
@software: Pycharm
@file: lettercombinations.py
@time: 2018/10/18 18:33
Requirement: Given a string containing only the number 2-9, returns all combinations of letters that it can represent.
The mapping of numbers to letters is given below (same as the phone keys). Note that 1 does not correspond to any letters.
2:ABC; 3:def; 4:ghi; 5:JKL; 6:mno; 7:PQRS; 8:TUV; 9:wxyz
Input: "23"
Output: ["ad", "AE", "AF", "BD", "Be", "BF", "CD", "CE", "CF"].
IDEA: First the letters represented by every number, and then 22 merge and merge. (Record parity)

Class solution (): Def __init__ (self): Pass def numtoletter (self, num): Dict = {2: ' abc ',                3: ' Def ', 4: "Ghi", 5: "JKL", 6: "MnO", 7: "Pqrs",        8: "TUV", 9: "WXYZ"} return Dict[num] def combine (self, str1, str2):            Len1 = Len (str1) len2 = Len (str2) combined = [] Temp_str = "For I in Range (LEN1): For j in Range (LEN2): Combined.append (temp_str+str1[i]+str2[j]) Temp_str = ' Return Co        mbined def lettercombinations (self, digits): "" ": Type Digits:str:rtype:list[str]" ""            if digits = = "": return [] length = len (digits) letters = [] for i in range (length): cur_num = Int (digits[i]) Cur_letter = Self.numtoletter (cur_num) letters.append (cur_letter ) If Len (Letters) = = 1:return [letters[0][t] for T in range (len (letters[0])) "While Len (Letters) > 1:cur_ Letters = [] If Len (Letters)% 2:for I in range ((Len (Letters)-1)/2): cur _letters.append (Self.combine (letters[i * 2], Letters[i * 2 + 1])) Cur_letters.append (Letters[len (Letters)-1 ]) Else:for I in range (len (Letters)/2): Cur_letters.append (Self.combine (le    Tters[i * 2], Letters[i * 2 + 1])) letters = Cur_letters return letters[0]if __name__ = = "__main__": Answer = solution () print answer.lettercombinations (' 2 ') # Print Len (answer.lettercombinations (' 2345 '))

Leetcode: Alphabetical combination of phone numbers

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.