17. Letter Combinations of a Phone Number

  • Question Description
    17. Letter Combinations of a Phone Number_第1张图片
  • My Key
package LeetCode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test {
     public static void main(String[] args) {
           String digits = "234";
           System.out.println(letterCombinations(digits));
     }
     public static List letterCombinations(String digits) {
           List answer = new ArrayList();
           if (digits == null || digits.length() == 0)
                 return answer;
           Map 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");
           return combine(digits, map);
     }
     public static List combine(String digtis, Map map) {
           List cur = new ArrayList();
           if (digtis.length() == 1) {
                 String digitsStr = map.get(Integer.parseInt(digtis));
                 for (int i = 0; i < digitsStr.length(); i++) {
                       cur.add("" + digitsStr.charAt(i));
                 }
                 return cur;
           }
           List pre = combine(digtis.substring(1), map);
           String head = map.get(Integer.parseInt(digtis.substring(0,  1)));
           for (int i = 0; i < pre.size(); i++) {
                 for (int j = 0; j < head.length(); j++) {
                       cur.add(head.charAt(j) + pre.get(i));
                 }
           }
           return cur;
     }
}

你可能感兴趣的:(Java,算法,LeetCode刷题)