LeetCode 17. Letter Combinations of a Phone Number

来源:互联网 发布:人工智能概念的提出 编辑:程序博客网 时间:2024/05/18 13:29
DescriptionHintsSubmissionsSolutions
  • Total Accepted: 143027
  • Total Submissions: 424827
  • Difficulty: Medium
  • Contributor: LeetCode

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.

给一个数字序列,返回把每个数字转换成对应的字母,所有可能的情况。

没想到什么特别好的办法,强行遍历了。

import java.util.HashMap;public class Solution {    public List<String> letterCombinations(String digits) {        List<String>ans = new ArrayList<String>();        if(digits==null||digits.length()==0){            return ans;        }        int len = digits.length();        HashMap<Character,String>map = new HashMap<Character,String>();        char[]c = {'2','3','4','5','6','7','8','9'};        String[]s = {"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};        for(int i=0;i<c.length;i++){            map.put(c[i],s[i]);        }        for(int i=0;i<len;i++){            String b = map.get(digits.charAt(i));            ans = combine(ans,b);        }        return ans;            }    public List<String> combine(List<String>list,String b){        List<String> ans = new ArrayList<String>();        if(list.size()==0){            for(int j=0;j<b.length();j++){                ans.add(String.valueOf(b.charAt(j)));            }            return ans;        }        for(int i=0;i<list.size();i++){            for(int j=0;j<b.length();j++){                ans.add(list.get(i) + b.charAt(j));            }        }        return ans;    }}

0 0
原创粉丝点击