leetcode 17 Letter Combinations of a Phone Number

题目详情

Given a digit string, return all possible letter combinations that the number could represent.
mapping of digit to letters (just like on the telephone buttons) is given below.
200px-Telephone-keypad2.png

这道题要求咱们给出,对于输入的按键组合,咱们须要返回按键所对应的全部可能的字符串。而按键和字母的对应关系如上图。git

想法

  • 这道题就是一种排列组合,对于一种按键组合咱们要按照输入顺序排列组合出全部的字符串。
  • 每一次按键咱们都会获得一系列字符串,如"2"获得"a","b","c"。这将成为下一次操做的前序字符串。
  • 咱们将字符串存储在linkedlist里面,经过peek操做依次取出前序字符串。对于每个不一样的前序字符串,咱们都要在其后面分别加上当前键所表示的不一样字符,再将得到的结果字符串加入linkedlist里面。

解法

public List<String> letterCombinations(String digits) {
        LinkedList<String> res = new LinkedList<String>(); 
        if(digits.length() == 0){
            return res;
        }
        String[] mapping = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};       
        res.add("");
        
        for(int i=0;i<digits.length();i++){
            int index = Character.getNumericValue(digits.charAt(i));
            while(res.peek().length() == i){
                String temp = res.remove();
                for(char c : mapping[index].toCharArray()){
                    res.add(temp+c);
                }
            }
            
        }      
        
        return res;
    }
相关文章
相关标签/搜索