Simple Java Solution


  • 0
    S

    public class Solution {
    public List<String> letterCombinations(String digits)
    {
    List<String> result=new ArrayList<String>();
    StringBuffer sb=new StringBuffer();
    int value=digits.length()-1;
    if(digits.length()==0)
    {
    return result;
    }
    letterCombinationsHelper(result,sb,0,value,digits);
    return result;
    }

    public void letterCombinationsHelper(List<String> result,StringBuffer sb,int index,int max,String digits)
    {
        if(index>max)
        {
            result.add(new String(sb.toString()));
            return;
        }
        
        char c=digits.charAt(index);
        char start='a';
        char end='c';
        /* map character from phone number to alphabet*/
        switch(c)
        {
            case '2':
              start='a';
              end='c';
              break;
            case '3':
              start='d';
              end='f';
              break;  
            case '4':
              start='g';
              end='i';
              break;
            case '5':
              start='j';
              end='l';
              break;
            case '6':
              start='m';
              end='o';
              break;
            case '7':
              start='p';
              end='s';
              break;
            case '8':
              start='t';
              end='v';
              break;
            case '9':
              start='w';
              end= 'z';
              break; 
              
              
              
        }
        /*iterate over all the character mapping and back track*/
        for(char val=start;val<=end;val++)
        {
            sb.append(val);
            letterCombinationsHelper(result,sb,index+1,max,digits);
            sb.deleteCharAt(sb.length()-1);
        }
        
    }
    

    }


Log in to reply
 

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