leetcode第17题:电话号码的字母组合

leetcode第17题:电话号码的字母组合

题目描述

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

题目来源

我的解法

十分繁琐,精确计算每个字符串待添加字符在字母数组中的位置。

class Solution {
    public List letterCombinations(String digits) {
         Listlist=new ArrayList<>();
		if(digits.length() == 0) return list;
		char[] letters = {'a','b','c','d','e','f','g','h','i','j','k','l'
				,'m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
		
        int[] nums = new int[digits.length()];
        for(int i = 0; i < digits.length(); i++) {
        	nums[i] = digits.charAt(i)-'0';
        }
        
        //一共有多少种字符串
        int totalCount = 1;
      	for(int i = 0; i < nums.length; i++ ) {
      		if(nums[i] == 7 || nums[i] == 9)totalCount *= 4;
      		else totalCount *= 3;
      	}
        list = new ArrayList(totalCount);
        
        int loc = 0;   //当前字符串需要加入的字符位置
        int count = 0;
        for(int k = 0; k < totalCount; k++) {
        	StringBuffer s = new StringBuffer();
        	count = totalCount;
            for(int i = 0; i < nums.length; i++) {
            	//内部位置
            	if(nums[i] != 7 && nums[i] != 9) {
            		count/= 3;
            		loc = Math.floorMod((k/count), 3);
            		loc = (nums[i]<7)?(nums[i]-2)*3+loc:(nums[i]-2)*3+loc+1;
            	}else {
            		count /= 4;
            		loc = Math.floorMod((k/count), 4);
            		loc = (nums[i]==7)?(nums[i]-2)*3+loc:(nums[i]-2)*3+loc+1;
            	}
            	s.append(letters[loc]);
            }  
            String str = s.toString();
            list.add(str);
        }
        
		return list;
    }
}

题解

网上大佬利用java一些类库里面方法解决,快速且简洁.

public List letterCombinations(String digits) {
		LinkedList ans = new LinkedList();
		if(digits.isEmpty()) return ans;
		String[] mapping = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
		ans.add("");
		for(int i =0; i

你可能感兴趣的:(leetcode第17题:电话号码的字母组合)