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



参考了官方答案后给出的代码(重点是维护一个队列):

class Solution {
    public List<String> letterCombinations(String digits) {
        String[] baseLetter= {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        List<String> letterCombinations=new ArrayList<String>();
        if(digits!=null&&!digits.equals(""))
        {
            letterCombinations.add("");
            for(int i=0;i<digits.length();i++)
            {
                int index=digits.charAt(i)-'0';
                while(letterCombinations.get(0).length()==i)
                {
                    String head=letterCombinations.get(0);
                    letterCombinations.remove(0);
                    for(char t:baseLetter[index].toCharArray())
                    {
                        letterCombinations.add(head+t);
                    }
                    
                }
            }
        }
        
        
        return letterCombinations;
    }



Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐