`
hcx2013
  • 浏览: 88926 次
社区版块
存档分类
最新评论

Letter Combinations of a Phone Number

 
阅读更多

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"].

Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

 

public class Solution {
    public List<String> letterCombinations(String digits) {
    	List<char[]> list = new ArrayList<char[]>();
        list.add(new char[]{' '});
        list.add(new char[]{});
        list.add(new char[]{'a','b','c'});
        list.add(new char[]{'d','e','f'});
        list.add(new char[]{'g','h','i'});
        list.add(new char[]{'j','k','l'});
        list.add(new char[]{'m','n','o'});
        list.add(new char[]{'p','q','r','s'});
        list.add(new char[]{'t','u','v'});
        list.add(new char[]{'w','x','y','z'});
        List<String> ret = new ArrayList<String>();
        ret.add("");
        return build(ret, list, digits, 0);
    }

	private List<String> build(List<String> ret, List<char[]> list,
			String digits, int i) {
		if (0 == digits.length()) {
			return new ArrayList<String>();
		}
		if (i == digits.length()) {
			return ret;
		}
		int pos = digits.charAt(i)-'0';
		char[] str = list.get(pos);
		if (str.length == 0) {
			return ret;
		}
		List<String> newRet = new ArrayList<String>();
		for (String s : ret) {
			for (char ch : str) {
				newRet.add(s+ch);
			}
		}
		return build(newRet, list, digits, i+1);
	}
}

 

0
5
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics