using ascii more simple using regression


  • 0
    M

    '''
    class Solution {
    List<String> li=new ArrayList<String>();
    String digit;
    public List<String> letterCombinations(String digits) {
    digit= digits;
    if(digits.length()>0)comb(0,"");
    return li;
    }
    void comb(int n,String t){
    if(n==digit.length()){
    li.add(t);
    return;
    }
    int num = Integer.parseInt(""+digit.charAt(n)),y=0;
    if(num>6){
    y=1;// 1 shift since 7 is mapped with 4 letters "pqrs"
    }
    if(num==9){y=2;//1 more shift since 9 is also mapped with 4 letters "wxyz"}
    if(num<2){
    return;// it has no letters no combination
    }
    int x=97+(num-2)*3; // finding the ascii number
    for(int i=0;i<3+y;i++){
    if(num>=8 && i==0){continue;}
    char c=(char)(x+i);
    String t1=t+""+c;
    // System.out.println(c);
    comb(n+1,t1);
    }
    }
    }
    '''


  • 0
    P
    class Solution {
        List<String> li=new ArrayList<String>();
        String digit;
        public List<String> letterCombinations(String digits) {
            digit= digits;
            if(digits.length()>0) comb(0,"");
            return li;
        }
    
        void comb(int n, String t) {
            if(n==digit.length()) {
                li.add(t);
                return;
            }
            int num = Integer.parseInt(""+digit.charAt(n)), y=0;
            if(num == 9) {
                y=2; //1 more shift since 9 is also mapped with 4 letters "wxyz"
            } else if (num > 6) {
                y=1; // 1 shift since 7 is mapped with 4 letters "pqrs"
            } else if (num < 2) {
                return; // it has no letters no combination
            }
            int x = 97 + (num-2)*3; // finding the ascii number
            for (int i = 0; i < 3 + y; i++) {
                if (num>=8 && i==0){
                    continue;
                }
                char c=(char)(x+i);
                String t1=t+""+c;
                // System.out.println(c);
                comb(n+1, t1);
            }
        }
    }
    

Log in to reply
 

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