LeetCode Letter Combinations of a Phone Number

来源:互联网 发布:高德导航 gps端口 编辑:程序博客网 时间:2024/06/04 18:43

题目:

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 List<String> letterCombinations(String digits){    List<String> list = new ArrayList<String>();    int length = digits.length();    if(length == 0 || digits == null)        return list;String[] map = new String[10];map[0] = "";map[1] = "";map[2] = "abc";map[3] = "def";map[4] = "ghi";map[5] = "jkl";map[6] = "mno";map[7] = "pqrs";map[8] = "tuv";map[9] = "wxyz";list.add("");    //一开始输入一个空for(int i = 0; i < digits.length(); i++){List<String> temp = new ArrayList<String>();  //临时变量String chars = map[digits.charAt(i) - '0'];for(int j = 0; j < chars.length(); j++){for(int k = 0; k < list.size(); k++){temp.add(list.get(k) + chars.charAt(j));   //这里是关键}}list = temp;}return list; }


0 0
原创粉丝点击