LeetCode刷题实战17: 电话号码的字母组合
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做电话号码的字母组合 ,我们先来看题面:
https://leetcode-cn.com/problems/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.
题意
样例
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
题解
class Solution {
public List<String> letterCombinations(String digits) {
// 数字与字母的对应关系
String[] map = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
List<String> res = new ArrayList<>();
if(digits.isEmpty())
return res;
// 图中树的根节点
res.add("");
// 遍历输入的数字
for(char c : digits.toCharArray()){
res = combine(map[c-'0'], res);
}
return res;
}
// 根据数字组合字母
private List<String> combine(String digits, List<String> list){
List<String> res = new ArrayList<>();
for(char c : digits.toCharArray()){
for(String s : list){
res.add(s+c);
}
}
return res;
}
}
今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力。
上期推文: