[Data structure and algorithm] The letter combination algorithm of the telephone number keyboard

Given a string containing only numbers 2-9, return all letter combinations it can represent.

1. Subject requirements
  • The mapping of numbers to letters is given as follows (same as phone buttons).
    Note: 1 does not correspond to any letters.

Insert picture description here

  • Examples are as follows:
	输入:"23"
	输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
  • Note: Although the answers above are arranged in lexicographical order, you can choose the order in which the answers are output.
Two, algorithm example
  • Ideas
    • The idea to solve this problem is relatively simple. Each number in a string has multiple letters, for example, 2 corresponds to: 3 abc, 3 corresponds to 3 def, 4 corresponds to 3 ghi, then 234 corresponds to 3 * 3 * 3 The combination of clocks, boiled down to the code, is a three-layer for loop. In other words, digits.count determines how many levels of for loops, then the corresponding N levels of for loops are nested, and it is better to use recursive methods.
    • The construction of the recursive function is still based on the idea of ​​the for loop. The difference is the exit mechanism of the recursive function, the combination of the corresponding letters and the collection conditions; and the processing of the index of the sub-loop.
  • Swift example one
	var listRes = [String]()

    let map : [Character:[Character]] = {
    
    
      return ["2":Array("abc"),
              "3":Array("def"),
              "4":Array("ghi"),
              "5":Array("jkl"),
              "6":Array("mno"),
              "7":Array("pqrs"),
              "8":Array("tuv"),
              "9":Array("wxyz")
              ]
    }()

    func letterCombinations(_ digits: String) -> [String] {
    
    
      if digits.count == 0 {
    
    
        return []
      }
      search("", Array(digits), 0)
      return listRes  
    }

    func search(_ s:String,_ digits: [Character],_ index:Int) {
    
    
      //! 1.terminator
      if index==digits.count {
    
    
        listRes.append(s)
        return
      }
    
      //! 2. process
      let letters = map[digits[index]]!
      for j in 0..<letters.count {
    
    
        //! drill down
        search(s+String(letters[j]), digits, index+1)
      }
  }
  • Swift example two
	let matchTable: [Int : [String]] = [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"]]
    
    func letterCombinations(_ digits: String) -> [String] {
    
    
        if digits == "" {
    
    
            // 避免map的时候返回 [""]
            return []
        }
        // Set中任何元素只出现一次
        var ret: Set<String> = []
        var i = 0
        while i < 5000 {
    
    
            var str = ""
            for c in digits {
    
    
                let val = Int(String(c))!
                // 取随机内容
                str += matchTable[val]!.randomElement()!
            }
            ret.insert(str)
            i += 1
        }
        return ret.map {
    
     (str) -> String in
            return str
        }
    }

Guess you like

Origin blog.csdn.net/Forever_wj/article/details/108655421