leetcode——17 Letter Combinations of a Phone Number

题目链接:https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/

Python实现

class Solution(object):
    def letterCombinations(self, digits):
        dicts = {'0': [''],
                 '1': [''],
                 '2': ['a', 'b', 'c'],
                 '3': ['d', 'e', 'f'],
                 '4': ['g', 'h', 'i'],
                 '5': ['j', 'k', 'l'],
                 '6': ['m', 'n', 'o'],
                 '7': ['p', 'q', 'r', 's'],
                 '8': ['t', 'u', 'v'],
                 '9': ['w', 'x', 'y', 'z']}
        if digits=='':
            res = []
        elif len(digits)==1:
            res = dicts[digits]
        else:
            l = dicts[digits[0]]
            i = 1
            while i< len(digits):   
                r = dicts[digits[i]]
                l = [ x+y  for x in l for y in r]
                i+=1
            res = l
        return res
    
m = Solution()
digits = '234'
m.letterCombinations(digits)

java实现

package test;

import java.util.ArrayList;
import java.util.List;

public class Leetcode_17 {
	
	public List<String> letterCombinations(String digits){
		List<String> reStrings = new ArrayList<String>();//用来保存最后的结果
		
		String[][] strings = {{},{},{"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"}};
		
		//输入为空字符串
		if (digits.length()==0) {
			return reStrings;
		}
		
		//输入包含一个数字的字符串
		if (digits.length()==1) {
			int x = Integer.parseInt(digits);
			
			for (String str : strings[x]) {
				reStrings.add(str);
			}
		}
		
		//输入包含两个及以上数字的字符串
		int y = Integer.parseInt(digits.substring(0, 1));//获得第一个
		for (String str : strings[y]) {
			for (String strs : letterCombinations(digits.substring(1))) {
				reStrings.add(str+strs);
			}
		}
		return reStrings;
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Leetcode_17 l = new Leetcode_17();
		List<String> reStrings = new ArrayList<String>();
		String digits = "23";
		reStrings = l.letterCombinations(digits);
		System.out.println(reStrings);
	}
}

猜你喜欢

转载自blog.csdn.net/u012063773/article/details/79470257
今日推荐