[LeetCode]17. Letter Combinations of a Phone Number电话号码的字母组合

时间:2022-02-03 06:06:43

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.

[LeetCode]17. Letter Combinations of a Phone Number电话号码的字母组合

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.

这题要求列出所有可能古德字符组合,我们先把1-9的字符列出来,然后从digits中一次取出数字代表的字符,然后做笛卡尔积的处理

这里的难点在于2个数的时候好处理,2层的循环就能解决,但是3个数,4个数怎么做呢?
4个数时,我们需要先求出2个数的笛卡尔积,然后再去处理第3个,第4个

所以我们在2层循环上,加上一层控制,在外部选定完i后,我们要在原来的字符串基础上加上第i个数字代表的字符,我们每次把list(0)的元素remove出来,然后加上

新的字符再添加到list的末尾,这样我们就可以根据list(0)的长度判断这一轮字符有没有全部加上,就像[b,c,ad,ae,af]这样,此时i=1,list.get(0).length()=1,这就说明还有这轮还没加完

直到[ad, ae, af, bd, be, bf, cd, ce, cf],此时i=1但list.get(0).length()=2,说明这轮结束,回到外层

class Solution {
public List<String> letterCombinations(String digits) {
List<String> list = new ArrayList<String>();
if(digits.isEmpty()) return list;
String[] str = new String[] {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
list.add("");
String temp = null;
for(int i = 0; i < digits.length(); i++) {
int k = Integer.parseInt(digits.charAt(i)+"");
while(list.get(0).length() == i)
{
temp = list.remove(0);
for(int j = 0; j < str[k].length(); j++){
list.add(temp + str[k].charAt(j));
}
}
}
return list;
}
}