*Java* very straightforward iterative solution (1ms)


  • 1
    E
    public List<String> letterCombinations(String digits) {
    	List<String> list = new ArrayList<String>();
    	if("".equals(digits)) return list;
    	
    	String[][] map = {{"a","b","c"}, {"d","e","f"}, {"g","h","i"}, {"j","k","l"}, {"m","n","o"}, {"p","q","r","s"}, {"t","u","v"}, {"w","x","y","z"}};
    
    	list.add("");
    	for(int i=0, L=digits.length(); i<L; i++) {
        	int digit = digits.charAt(i)-'2';
        	List<String> prev = list;
        	list = new ArrayList<String>();
        	for(String str1 : map[digit]) {
        		for(String str2 : prev) {
        			list.add(str2 + str1);
        		}
        	}
    	}
    	return list;
    }

  • 0
    D

    have you tested this program?


  • 0
    E

    Do you see any problem? I just submitted it again and it is accepted.


  • 0
    D

    correct it is accepted but in custom test case with input "123" it is not working. I think you have not handled 1 and 0 digits.


  • 0
    E

    I guess for this problem we don't need to consider for error cases such as "123" because 1 is mapped to some weird symbol rather than a letter. If you want to include those error cases, here is the corresponding code with easy modification (notice that I added):

    public List<String> letterCombinations(String digits) {
    	List<String> list = new ArrayList<String>();
    	if(!digits.matches("[2-9]+")) return list; // error cases
    	if("".equals(digits)) return list;
    	
    	String[][] map = {{"a","b","c"}, {"d","e","f"}, {"g","h","i"}, {"j","k","l"}, {"m","n","o"}, {"p","q","r","s"}, {"t","u","v"}, {"w","x","y","z"}};
    	list.add("");
    	for(int i=0, L=digits.length(); i<L; i++) {
        	int digit = digits.charAt(i)-'0';
        	List<String> prev = list;
        	list = new ArrayList<String>();
        	for(String str1 : map[digit]) {
        		for(String str2 : prev) {
        			list.add(str2 + str1);
        		}
        	}
    	}
    	return list;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.