问题描述:
If a=1, b=2, c=3,....z=26. Given a string, find all possible codes that string can generate. Give a count as well as print the strings.
For example:
Input: "1123". You need to general all valid alphabet codes from this string.
Output List
aabc //a = 1, a = 1, b = 2, c = 3
kbc // since k is 11, b = 2, c= 3
alc // a = 1, l = 12, c = 3
aaw // a= 1, a =1, w= 23
kw // k = 11, w = 23
问题解决:
这个算法没有什么特别的,直接递归就好了。分为三种情况,第一,直接把一位数字转换为字母,然后递归;第二种,如果该位数字为1,那么可以将该位以及下一位一起转变为一个字母,再递归;第三种,如果该位为2且下一位小于等于6,这将该位以及下一位一起转变为一个字母,再递归。
1: public Set<String> decode(String prefix, String code) {
2: Set<String> set = new HashSet<String>();
3: if (code.length() == 0) {
4: set.add(prefix);
5: return set;
6: }
7:
8: if (code.charAt(0) == '0')
9: return set;
10:
11: set.addAll(decode(prefix + (char) (code.charAt(0) - '1' + 'a'),
12: code.substring(1)));
13: if (code.length() >= 2 && code.charAt(0) == '1') {
14: set.addAll(decode(
15: prefix + (char) (10 + code.charAt(1) - '1' + 'a'),
16: code.substring(2)));
17: }
18: if (code.length() >= 2 && code.charAt(0) == '2'
19: && code.charAt(1) <= '6') {
20: set.addAll(decode(
21: prefix + (char) (20 + code.charAt(1) - '1' + 'a'),
22: code.substring(2)));
23: }
24: return set;
25: }
题目以及解答来自careercup