leetCode 17.Letter Combinations of a Phone Number(電話數字對應的字母組合) 解題思路和方法
阿新 • • 發佈:2019-02-07
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.
思路:演算法上很簡單,就是將每個數字對應的字元迴圈相加即可,一次一次的遍歷窮舉即可。
詳細程式碼和註釋如下:
public class Solution { //儲存為靜態變數,效率更高 public static String[] map = new String[128]; public List<String> letterCombinations(String digits) { List<String> list = new ArrayList<String>(); char[] ch = digits.toCharArray(); if(ch.length == 0) return list; //按ACSII碼儲存 map['0'] = ""; map['1'] = ""; map['2'] = "abc"; map['3'] = "def"; map['4'] = "ghi"; map['5'] = "jkl"; map['6'] = "mno"; map['7'] = "pqrs"; map['8'] = "tuv"; map['9'] = "wxyz"; for(int i = 0; i < ch.length; i++){ list = addList(ch[i],list); } return list; } //將每個數字對應的字元與list相加後返回 public static List<String> addList(char c,List<String> list){ String s = map[c];//讀取對應字串 if(list.size() == 0){//如果是第一個字串 for(int i = 0; i < s.length();i++){ list.add(s.charAt(i) + ""); } return list; } else{//不是則迴圈相加 List<String> al = new ArrayList<String>(); for(int i = 0; i < s.length();i++){ for(int j = 0; j < list.size(); j++){ al.add(list.get(j) + s.charAt(i)); } } return al; } } }