Python: Iterative w/o any special python library.


  • 3
    H
    class Solution(object):
        def letterCombinations(self, digits):
            """
            :type digits: str
            :rtype: List[str]
            """
            
            if not len(digits):
                return []
      
            phones = {"1":"" , "2":"abc" , "3":"def" , "4":"ghi" , "5":"jkl" , "6":"mno" , "7":"pqrs" , "8":"tuv" , "9":"wxyz"}
                
            results = []
            results.append("")
            
            if not digits.isdigit():
                return results
                
            for digit in digits:
                if digit == "1":
                    continue
                word = phones[digit]
                temp = []
                for alphabet in word:
                    for result in results:
                        temp.append(result+alphabet)
                results = temp
            
            return results

  • 0
    A

    Hi, I would like to know why you add results.append(""). I cannot get the right answer when I didnt add this. Any answer will be appreciated.


  • 0
    G

    For string operation ''+'a' is valid which end up a new string object. Before we start to iterate, we need to initiate a string


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.