Saturday, January 10, 2015

Letter Combinations of a Phone Number (LeetCode String)

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

Idea: Depth-first search. First initial the digit - char[] mapping, e.g. 2->{a, b, c}. Then add the char in char[] one by one and continue to append the char created by the next digit. Then backtrack to the original point to add another char. For example, "23"
2->{a,b,c}
3->{d,e,f}

a, ad, ae, af
b, bd, be, bf
c, cd, ce, cf.

When the length of a temporary string matches the required length digits.length(), add it to the result.

Time: O(n^4) since each digit has maximum 4 choices.
Space: O(n) (each time we just cache a temporary string)

Code:
 public class Solution {  
   public List<String> letterCombinations(String digits) {  
     List<String> result=new ArrayList<String>();  
     if(digits.length()==0)  
     {    
       result.add("");  
       return result;  
     }  
     StringBuilder path=new StringBuilder();  
     dfs(result,path,digits,0);  
     return result;  
   }  
   public void dfs(List<String> result,StringBuilder path,String digits,int cur)  
   {  
     if(path.length()==digits.length())  
     {  
       result.add(path.toString());  
       return;  
     }  
     int value=(int)(digits.charAt(cur)-'0');  
     for(char c:digitToString(value))  
     {  
       path.append(c);  
       dfs(result,path,digits,cur+1);  
       path.deleteCharAt(path.length()-1);  
     }  
   }  
   HashMap<Integer,char[]> computed=new HashMap<Integer,char[]>();  
   public char[] digitToString(int i)  
   {  
     if(computed.containsKey(i))  
       return computed.get(i);  
     String[] letters={  
       " ",  
       " ",  
       "abc",  
       "def",  
       "ghi",  
       "jkl",  
       "mno",  
       "qprs",  
       "tuv",  
       "wxyz"  
     };  
     char[] result=letters[i].toCharArray();  
     computed.put(i,result);  
     return result;  
   }  
 }  

No comments:

Post a Comment