zoukankan      html  css  js  c++  java
  • phone number

    problem description:

    you should change the given digits string into possible letter string according to the phone keyboards.

    i.e.

    input '23'

    output ['ad','ae','af','bd','be','bf','cd','ce','cf']

    the python solution 

    first you should realize this a iteration process, so you can use many iterate process to handle this problem.reduce fuction is a important iteration function in python.reduce(function , iterator, start),this is it's base form,the first function must have two parameter, the first parameter will be used to record the result,and the other just to fetch the number in the iterator.start can be omitted, then the fisrt result fetch from the iterator the first num,if not the start means the original result.After know the reduce fuction, we know can use it to solve this problem.

    in python:

    lists = ['a','b']

    for in in 'abc':

      lists += i 

    return lists

    then the lists will be ['aa','ab','ac','ba','bb','bc'],base on this feacture, so give the below solution 

    class Solution(object):
        def letterCombinations(self, digits):
            """
            :type digits: str
            :rtype: List[str]
            """
            if digits == '': return []
            phone = {'2':'abc','3':'def','4':'ghi','5':'jkl',
            '6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
            return reduce(lambda x,y:[a+b for a in x for b in phone[y]],digits, [''])

    this solution is so smart.Thanks to huxley  publish such a great  method to deal with this issue.

    I f you still can not understand this method, there is another simple way.

    class Solution(object):
        def letterCombinations(self, digits):
            """
            :type digits: str
            :rtype: List[str]
            """
            if len(digits) == 0:
                return []
            phone = {'2':'abc','3':'def','4':'ghi','5':'jkl',
            '6':'mno','7':'pqrs','8':'tuv','9':'wxyz'} 
           
            result = ['']
            for i in digits:
                temp = []
                for j in result:
                    for k in phone[i]:
                        temp.append(j + k)
                result = temp
            return result
  • 相关阅读:
    tinyxml优化之一
    vs下C++内存泄露检测
    Cocos2d-x项目移植到WP8系列之九:使用自定义shader
    [leetcode 双周赛 11] 1228 等差数列中缺失的数字
    [leetcode 周赛 158] 1224 最大相等频率
    [leetcode 周赛 158] 1223 掷骰子模拟
    [leetcode 周赛 158] 1222 可以攻击国王的皇后
    [leetcode 周赛 158] 1221 分割平衡字符串
    [leetcode 周赛 157] 1220 统计元音字母序列的数目
    [leetcode 周赛 157] 1219 黄金矿工
  • 原文地址:https://www.cnblogs.com/whatyouknow123/p/6702780.html
Copyright © 2011-2022 走看看