Generate all possible Letter combinations from numbers.


  • 1
    M

    If a=1, b=2, c=3,....z=26. Given a string, find all possible codes that string can generate. Give a count as well as print the strings.

    For example:
    Input: "1123". You need to general all valid alphabet codes from this string.

    Output List
    aabc //a = 1, a = 1, b = 2, c = 3
    kbc // since k is 11, b = 2, c= 3
    alc // a = 1, l = 12, c = 3
    aaw // a= 1, a =1, w= 23
    kw // k = 11, w = 23


  • 0
    B

  • 0
    L

    I tried this today. Here is the basic code that was tested only on this example:

    
      public static void possibleCodes(String input, String s,
          List<String> list)
      {
        if (input.isEmpty())
        {
          list.add(s);
          return;
        }
        for (int i = 1; i <= 2; i++)
        {
          if (input.length() >= i)
          {
            String sub = input.substring(0, i);// 1
            int val = Integer.valueOf(sub);
            if (val > 26)
            {
              continue;
            }
            possibleCodes(input.substring(i), s + numToChar(sub), list);
          }
        }
      }
    
    
    
      private static String numToChar(String s)
      {
        Integer i = Integer.valueOf(s);
        StringBuilder builder = new StringBuilder();
        builder.append((char) ('a' - 1 + i));
        return builder.toString();
      }
    

Log in to reply
 

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