【leetcode】Letter Combinations of a Phone Number

  • 建一个二位char数组对应2,3,4……9char值,注意2对应abc9对应wxyz
  • 对于输入的stringcharAt取出对应数,注意要减去'0'才是int数,因为是错位对应,从2开始,所以还要减去1,因为数组索引,所以还要减去1
  • 需要用到递归
  • 如果取数字的位置i大于等于电话号码的长度,将sb中的数tostring添加到返回ret
  • 删掉最后一个字母,换另外一个字母
  • 如果最后一个字母遍历完,遍历倒数第二个字母
  • 最终遍历完成输出ret
  • ret是链表

    package leetcode;

       

       

    import java.util.ArrayList;

       

    /**

    * Given a digit string, return all possible letter combinations that the number

    * could represent.

    *

    * A mapping of digit to letters (just like on the telephone buttons) is given below.

    *

    * Input:Digit string "23"

    * Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

    */

       

    public class LetterCombinationsofaPhoneNumber {

    private char[][] map = new char[][] { { 'a', 'b', 'c' }, { 'd', 'e', 'f' },

    { 'g', 'h', 'i' }, { 'j', 'k', 'l' }, { 'm', 'n', 'o' },

    { 'p', 'q', 'r', 's' }, { 't', 'u', 'v' }, { 'w', 'x', 'y', 'z' } };

       

    public ArrayList<String> letterCombinations(String digits) {

    ArrayList<String> ret = new ArrayList<String>();

    StringBuilder sb = new StringBuilder();

    letterCombinations(digits, 0, sb, ret);

    return ret;

    }

       

    private void letterCombinations(String digits, int i, StringBuilder sb,

    ArrayList<String> ret) {

    if (i >= digits.length()) {

    ret.add(sb.toString());

    } else {

    int index = digits.charAt(i) - '1' - 1;

    int size = map[index].length;

    for (int j = 0; j < size; j++) {

    sb.append(map[index][j]);

    letterCombinations(digits, i + 1, sb, ret);

    sb.deleteCharAt(sb.length() - 1);

    }

    }

    }

    }

       

posted @ 2015-03-25 19:48  keedor  阅读(125)  评论(0编辑  收藏  举报