1. 程式人生 > >leetcode-17-電話號碼的字母組合(letter combination of a phone number)-java

leetcode-17-電話號碼的字母組合(letter combination of a phone number)-java

題目及測試

package pid017;
/* 電話號碼的字母組合

給定一個僅包含數字 2-9 的字串,返回所有它能表示的字母組合。

給出數字到字母的對映如下(與電話按鍵相同)。注意 1 不對應任何字母。
	2 abc
	3 def
	4 ghi
	5 jkl
	6 mno
	7 pqrs
	8 tuv
	9 wxyz
示例:

輸入:"23"
輸出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

說明:
儘管上面的答案是按字典序排列的,但是你可以任意選擇答案輸出的順序。


*/

import java.util.List;

public class main {
	
	public static void main(String[] args) {
		String[] testTable = {"24","23","6574"};
		for (String ito : testTable) {
			test(ito);
		}
	}
		 
	private static void test(String ito) {
		Solution solution = new Solution();
		List<String> rtn;
		long begin = System.currentTimeMillis();
		System.out.println("ito="+ito);
		System.out.println();
		//開始時列印陣列
		
		rtn= solution.letterCombinations(ito);//執行程式
		long end = System.currentTimeMillis();	
		
		System.out.println("rtn=" );
		for(int i=0;i<rtn.size();i++){
			System.out.print(rtn.get(i)+" ");	
		}
		System.out.println();
		System.out.println("耗時:" + (end - begin) + "ms");
		System.out.println("-------------------");
	}

}

解法1(成功,5ms,較慢)

在類中建立一個數字對應字母的map,和對應的結果list
進入combine("",digits)
第一個字串為當前字串,後面的為還能加上的數字字串
每次從陣列字串中取最前一位,得到對應的char陣列,將nowStr+對應的陣列(用for迴圈,分別加幾次),然後再次combine
如果remain為“”,說明一小次迴圈完成,將nowstr加入result

package pid017;

import java.sql.Array;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

public class Solution {
	/*2 abc
	3 def
	4 ghi
	5 jkl
	6 mno
	7 pqrs
	8 tuv
	9 wxyz*/

	HashMap<Character, char[]> map=new HashMap<>();
	List<String> result=new ArrayList<>();
	public List<String> letterCombinations(String digits) {  
		int length=digits.length();
		if(length==0){			
			return result;
		}
		
	    map.put('2', new char[]{'a','b','c'});
	    map.put('3', new char[]{'d','e','f'});
	    map.put('4', new char[]{'g','h','i'});
	    map.put('5', new char[]{'j','k','l'});
	    map.put('6', new char[]{'m','n','o'});
	    map.put('7', new char[]{'p','q','r','s'});
	    map.put('8', new char[]{'t','u','v'});
	    map.put('9', new char[]{'w','x','y','z'});
	    combine("",digits);
		
		return result;
	 }
	public void combine(String nowStr,String remain){
		int length=remain.length();
		if(length==0){
			result.add(nowStr);
			return;
		}
		Character now=remain.charAt(0);
		for(char nowChar:map.get(now)){
			combine(nowStr+nowChar,remain.substring(1));
		}
	}

}

其餘做法基本思路也是這樣,可以將hashmap 改為char[][]陣列,每個數字的字母放在對應的地方