鱼C论坛

 找回密码
 立即注册
查看: 1685|回复: 0

[学习笔记] leetcode 17. Letter Combinations of a Phone Number 谷歌面试题

[复制链接]
发表于 2019-8-18 04:39:53 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
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"].
Note:

Although the above answer is in lexicographical order, your answer could be in any order you want.

200px-Telephone-keypad2.svg.png
class Solution {
    public static List<String> letterCombinations(String digits) {
        
        List<String> fi  = new ArrayList<String>();
        
        if(digits == null || digits.length() == 0){
            
            return fi;
        }
        
        generateString(digits, fi , "");
        
        return fi;
        
    }
    
    public static void generateString(String digits, List<String> fi,String result){
            
            if(digits.length() == 0) {
                    
                    fi.add(result);
                    
                    return;
            }
        
            String head = get_head(digits);
            
            String a = "";
            
            
            switch (head) {
        case "2":
            a = "abc";
            break;
        case "3":
            a = "def";
            break;
        case "4":
            a = "ghi";
            break;
        case "5":
            a = "jkl";
            break;
        case "6":
            a = "mno";
            break;
        case "7":
            a = "pqrs";
            break;
        case "8":
            a = "tuv";
            break;
        case "9":
            a = "wxyz";
            break;
        default:
            a = "";
            break;
        }
            
            for(int i = 0; i < a.length(); i++) {
                    
                    result = result + a.substring(i,i+1);
                    
                    generateString(digits.substring(1,digits.length()),fi,result);
                    
                    result = result.substring(0,result.length()-1);
                    
            }
        
    }
    
    public static String get_head(String digits){
        
        if(digits == null || digits == ""){
            
            return null;
        }
        
        return digits.substring(0,1);
    }
}

18.jpg

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-20 14:16

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表