Simple Solution beats 39% using Delimiter and Backtracking


  • 0

    Hi I have solved this question using delimiter.
    There are two types of numbers like
    3 digit: 3 ("abc"), 4 ("def")
    4 digit: 7 ("pqrs"), 9 ("wxyz")

    So i have appended delimiter "Z" to 3 digit numbers . so as to convert those 3 digit to 4 digits.

           public List<String> letterCombinations(String inp) {
      
        
        String s[]={"abcZ","defZ","ghiZ","jklZ","mnoZ","pqrs","tuvZ","wxyz"};
        List <String> row= new ArrayList<String>();
        String temp="";
          if(inp.length()==0)
        return row;
        letterComibinations1(inp,s,row,temp,0);
        return row;
    }
    
    
    public void letterComibinations1(String inp, String s[], List<String> row, String temp,int j){
        if(j==inp.length())
        {  row.add(temp);
            return;
        }
        
        
        for(int i=0;i<4;i++)
        {
            
            if(s[Character.getNumericValue(inp.charAt(j))-2].charAt(i)=='Z')continue;
            temp+= s[Character.getNumericValue(inp.charAt(j))-2].charAt(i);
                letterComibinations1(inp,s,row,temp,j+1);
                temp=temp.substring(0,temp.length()-1);
                
             
            
        }
    }
    

    }


Log in to reply
 

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