LeeCode-------Letter Combinations of a Phone Number 解法
题目如下:
Given a digit string, 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.
![]()
Input:Digit string "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.
大概翻译:
给出一个整数组成的字符串,给出这些数字所能代表的所有字母组合。
数字和字母的映射关系(就像电话上的按钮一样)在下面的图片中给出。
注意:
尽管上面的答案是字典顺序,但是你的答案可以按照你想要的任何顺序来排列。
首先,考虑字母与数字有相应的映射关系,为了比较直观的展示,选择数组来存放会比较好。
其次,注意到数字的先后顺序对于字符串的结果是有影响的,后出现的数字可能代表的字符一定在先出现的数字可能代表的字符的后面,所以按顺序解析给定字符串就可以了。
【Java代码】如下:
public class Solution { public List<String> letterCombinations(String digits) { //定义数字和字母的对应关系 char[] two = {'a', 'b', 'c'}; char[] three = {'d', 'e', 'f'}; char[] four = {'g', 'h', 'i'}; char[] five = {'j', 'k', 'l'}; char[] six = {'m', 'n', 'o'}; char[] seven = {'p', 'q', 'r', 's'}; char[] eight = {'t', 'u', 'v'}; char[] nine = {'w', 'x', 'y', 'z'}; List<String> result = new ArrayList<String>(); //单独拿出String中的字符逐一判断 for(int i = 0; i < digits.length(); i++){ char ch = digits.charAt(i); if(ch == '2'){ result = combat(result, two); }else if(ch == '3'){ result = combat(result,three); }else if(ch == '4'){ result = combat(result,four); }else if(ch == '5'){ result = combat(result,five); }else if(ch == '6'){ result = combat(result,six); }else if(ch == '7'){ result = combat(result,seven); }else if(ch == '8'){ result = combat(result,eight); }else if(ch == '9'){ result = combat(result,nine); } } return result; } //连接字符的功能函数 public List<String> combat(List<String> list, char[] sz){ List<String> newList = new ArrayList<String>(); if(list.size() <= 0){ for(int i = 0; i < sz.length; i++){ newList.add(sz[i] + ""); } } for(int i = 0; i < list.size(); i++){ String str = list.get(i); for(int j = 0; j < sz.length; j++){ //在已有的字符串序列后加入新的字符 newList.add(str + sz[j]); } } return newList; } }
当然,上面的代码只是为了阅读方便,还可以进行优化。
优化方法就是创建一个二维数组,将上面的数组封装到一个二维数组中,直接根据给定的String字符串取出char后转换成数字下标取出对应字母数组。
具体实现方法交给读者自行实现。
如果有任何问题,欢迎跟我联系:xiaomenxiaomen@qq.com
我的github地址:github.com/WXRain

浙公网安备 33010602011771号