Letter Combination of phone number

来源:互联网 发布:淘宝定做衣服 编辑:程序博客网 时间:2024/05/17 02:12

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{public List<String> letterCombinations(String digits){LinkedList<String> ans = new LinkedList<String>();String[] mapping = {"0","1","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};if(digits == null || digits.length() == 0){return ans;}ans.add("");for(int i=0; i<digits.length();i++){int x = Character.getNumericValue(digits.charAt(i));while(ans.peek().length() == i){//取出第一个字符串,将其长度与当前数字的位数进行比较String t = ans.removeFirst();//Or  ans.remove();for(char s : mapping[x].toCharArray()){ans.add(t+s);}}}return ans;}}