DEV Community

Takahiro Kudo
Takahiro Kudo

Posted on

2 1

LeetCode "Letter Combinations of a Phone Number"

I thought of separating the process of combinations is a good approach.

Letter Combinations of a Phone Number

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:

        if not digits:
            return []

        DecimalToChar = {'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':[' ']
                        }

        def combinations(strs1, strs2):
            combs = []
            for s1 in strs1:
                for s2 in strs2:
                    combs.append(s1 + s2)
            return combs


        strs = [DecimalToChar[s] for s in digits]        
        combs = strs[0]
        for s in strs[1:]:
            combs = combinations(combs, s)

        return combs
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay