CodingTour
ARTS #48

Algorithm

本周选择的算法题是:Letter Combinations of a Phone Number

规则如下:

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

Example:

Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:

Although the above answer is in lexicographical order, your answer could be in any order you want.

Solution

Runtime:24 ms,快过 91.28%。

Memory:13.6 MB,低于 5.88%。

class Solution:
    map = {
        '2': 'abc',
        '3': 'def',
        '4': 'ghi',
        '5': 'jkl',
        '6': 'mno',
        '7': 'pqrs',
        '8': 'tuv',
        '9': 'wxyz',
    }
    def letterCombinations(self, digits: str) -> List[str]:
        ans = []
        def recursive(letters, remain):
            if len(remain) == 0:
                ans.append(letters)
            else:
                for letter in Solution.map[remain[0]]:
                    recursive(letters + letter, remain[1:])

        if digits: recursive('', digits)
        return ans

基于栈的 BFS 算法:

class Solution:
    map = {
        '2': 'abc',
        '3': 'def',
        '4': 'ghi',
        '5': 'jkl',
        '6': 'mno',
        '7': 'pqrs',
        '8': 'tuv',
        '9': 'wxyz',
    }
    def letterCombinations(self, digits: str) -> List[str]:
        if not digits: return []
        ans = [""]
        while ans and len(ans[0]) != len(digits):
            letter = ans.pop(0)
            for char in Solution.map[digits[len(letter)]]:
                ans.append(letter + char)
        return ans

还可以将字典优化成数组,减少内存的的占用:

# map = {
#   '2': 'abc',
#   '3': 'def',
#   '4': 'ghi',
#   '5': 'jkl',
#   '6': 'mno',
#   '7': 'pqrs',
#   '8': 'tuv',
#   '9': 'wxyz',
# }
map = [ 'abc','def','ghi','jkl','mno','pqrs','tuv','wxyz' ]

Review

How to create your own pull to refresh / custom refresh indicator widget in Flutter. 一个 Flutter 下拉刷新 widget 的介绍,可以感受下和 iOS 控件开发体验有何不同。

Tip

在 LLDB 中对所有的 +load 方法添加断点:

br s -r "\+\[.+ load\]$"

Share

学习与认知,是有复利效应的,很多内容都可以触类旁通。

我们能做到的就是,不断丰富自己的知识和思想体系,慢慢积累,说不定,哪天就用到了。当然,现在大家的生活节奏都很快,更需要计划性和体系化。