Leetcode 17 Letter Combinations of a Phone Number

problem:

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. A mapping of digit to letters is just like on the telephone buttons.

Example:

Input: “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].

Analysis:

This problem is pretty much like a recursive problem. We can use dfs to solve it. First of all I would draw the tree. Then write the code directly.

在这里插入图片描述

Here are something we should notice:
string本身是不可改变的,它只能赋值一次,每一次内容发生改变,都会生成一个新的对象,然后原有的对象引用新的对象,而每一次生成新对象都会对系统性能产生影响,这会降低.NET编译器的工作效率.
StringBuilder类则不同,每次操作都是对自身对象进行操作,而不是生成新的对象,其所占空间会随着内容的增加而扩充,这样,在做大量的修改操作时,不会因生成大量匿名对象而影响系统性能

public static List<String> letterCombinations1(String digits) {
		
		// corner case 
		if (digits.length() == 0 || digits == null) {
			return null;
		}
		
		
		// first build the result 
		List<String> res = new LinkedList<>();
		// String[] map = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
		HashMap<Integer, String> map = new HashMap<>();
		map.put(0, "");
		map.put(1, "");
		map.put(2, "abc");
		map.put(3, "def");
		map.put(4, "ghi");
		map.put(5, "jkl");
		map.put(6, "mno");
		map.put(7, "qprs");
		map.put(8, "tuv");
		map.put(9, "wxyz");
		
		
		StringBuilder temp = new StringBuilder();
		
		dfs(res, map, temp, 0, digits);
		
		return res;
	}
	
	public static void dfs(List<String> res, HashMap<Integer, String> map, StringBuilder temp, int layer, String digits ) {
		// basic case
		if (layer == digits.length()) {
			res.add(temp.toString());
			return;
		}
				
		// find the first digit
		int x = digits.charAt(layer) - '0';
		String value = map.get(x);
		for (int i=0; i<value.length(); i++) {
			// add the first char into stringBuilder
			temp.append(value.charAt(i));
			dfs(res, map, temp, layer+1, digits);
			temp.deleteCharAt(temp.length() - 1);		
		}	
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值