17. 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”].
python
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if len(digits) == 0:
return ""
dic = {
'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']
}
result = dic[digits[0]]
if len(digits) == 1:
return result
for i in range(1, len(digits)):
list = []
for r in result:
for c in dic[digits[i]]:
list.append(r+c)
result = list
return result
java:
class Solution {
public List<String> letterCombinations(String digits) {
List<String> list = new ArrayList<>();
Map<Character, String> map = new HashMap<>();
map.put('2', "abc");
map.put('3', "def");
map.put('4', "ghi");
map.put('5', "jkl");
map.put('6', "mno");
map.put('7', "pqrs");
map.put('8', "tuv");
map.put('9', "wxyz");
if(digits.length()==0) return list;
char[] letter = digits.toCharArray();
list.add("");
for(char c: letter){
list = merge(list,map.get(c));
}
return list;
}
private List<String> merge(List<String> list ,String c){
List<String> res = new ArrayList<>();
for(String str: list){
for(int i=0;i<c.length();i++){
res.add(str+c.charAt(i));
}
}
return res;
}
}
java相较于python比较复杂,使用了map 这里对于toCharArray()函数进行了复习,同时Map的相关知识进行了巩固,字符串与数组不同不能直接使用index进行调用,需要使用CharAt()函数,同时遍历,可以在list和数组中间使用,但是不能在字符串中间使用,调用merge函数的时候需要将list赋值,不然无法进行相加。