Problem

Given a digit string, return all possible letter combinations that the number could represent. (Check out your cellphone to see the mappings)

Example

Input : Digit string "23"
Output : ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

JavaScript Code


function letterCombinations(digits) {
    var map = [];
    map[2]="abc";
    map[3]="def";
    map[4]="ghi";
    map[5]="jkl";
    map[6]="mno";
    map[7]="pqrs";
    map[8]="tuv";
    map[9]="wxyz";
    map[0]="";
 
    var result = [];
 
    if(digits == null || digits.length == 0)
        return result;
 
    var temp = [];
    getString(digits, temp, result, map);
 
    return result;
}
 
function getString(digits, temp, result, map){
    if(digits.length == 0){
        var arr = [];
        for(var i=0; i<temp.length; i++){
            arr[i] = temp[i];
        }
        result.push(arr.join(''));
        return;
    }
 
    var curr = parseInt(digits.substring(0,1));
    var letters = map[curr];
    for(var i=0; i<letters.length; i++){
        temp.push(letters.charAt(i));
        getString(digits.substring(1), temp, result, map);
        temp.pop();
    }
}

console.log(letterCombinations("23"));

3 comments:

  1. thanks for sharing very useful information and very fantastic job. learning alphabets for children

    ReplyDelete
  2. These companies primarily offer reverse cell phone lookup services for both unlisted phone numbers and cellular numbers alike. check over here

    ReplyDelete
  3. The same is the case even in the case of cheap international free phonecalls where the users have the two main options including calling cards and VoIP. Both of these ways have their own unique sophistication, but the main advantage is the affordable price at making long distance calls.

    ReplyDelete

Blogroll

Follow this blog by Email

Popular Posts