code Combinations

给定一个数列,比如1234,将它match到字母上,1是A,2是B等等,那么1234可以是
ABCD
但是还可以是12是L,所以1234也可以写作
LCD 或者
AWD

package string;

import java.util.*;

public class DecodeCombination {

	// http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=188433&extra=page%3D1%26filter%3Dsortid%26sortid%3D311%26searchoption%5B3046%5D%5Bvalue%5D%3D2%26searchoption%5B3046%5D%5Btype%5D%3Dradio%26sortid%3D311
	public static void main(String[] args) {
		List<String> strs = generateCombination("1234");
		for (String str : strs) {
			System.out.println(str);
		}
		//ABCD AWD LCD
	}

	public static List<String> generateCombination(String s) {
		List<String> ret = new LinkedList<String>();
		if (s == null || s.length() == 0) {
			return ret;
		}
		String[] map = { "", "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" };
		dfs(s, ret, 0, "", map);
		return ret;
	}

	static void dfs(String s, List<String> ret, int index, String item, String[] map) {
		if (index >= s.length()) {
			ret.add(item);
			return;
		}

		int i = s.charAt(index) - '0';
		dfs(s, ret, index + 1, item + map[i], map);

		// 如果可以有两位数,比如"24"就可以对应"X",就要继续递归。而"27"就没有的对应。
		if (index < s.length() - 1) {
			int j = s.charAt(index + 1) - '0';
			if (i * 10 + j <= 26) {
				dfs(s, ret, index + 2, item + map[i * 10 + j], map);
			}
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值