Algorithm-Letter Combinations of a Phone Number

Algorithm Letter Combinations of a Phone Number

Description

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.


image.png

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.

Submission

package com.cctoken.algorithm;

import java.util.LinkedList;
import java.util.List;

/**
 * @author chenchao
 */
public class LetterCombination {

  public List<String> letterCombinations(String digits) {
    String[] mapDigits = new String[]{"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    List<String> res = new LinkedList<String>();
    if (digits.length() == 0) {
      return res;
    }
    res.add("");
    for (int i = 0; i < digits.length(); ++i) {
      res = combineTwoString(mapDigits[digits.charAt(i) - '0' - 2], res);
    }
    return res;

  }

  // define a function that join the string and the previous result
  // and return the list result
  public List<String> combineTwoString(String left, List<String> prevStr) {
    List<String> res = new LinkedList<String>();
    for (String prev : prevStr) {
      for (int i = 0; i < left.length(); ++i) {
        res.add(prev + left.charAt(i));
      }
    }
    return res;
  }


  public static void main(String[] args) {
    String digits = "23";
    List<String> res = new LetterCombination().letterCombinations(digits);
  }
}

Solution

解题思路:手机九宫格按键,每个数字对应相应的字符,枚举出所有可能的结果。

我们首先定义一个转换函数,combineTwoString(函数名定义的不是很好),将第一个参数所有单个字符放在 prevStr 里的每个元素后面

规定起始参数 prevStr 为 ""

image.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容