解析:
f(i)中各个字母出现的次数 = f(i - 1)中 各个字母出现的次数 + f(i - 2)中各个字母出现的次数.
我的思路是把字母和次数存储在一个双列集合中,然后进行计数运算,但是自己写的代码太麻烦了,即使也AC了,真心觉得自己很渣,看了别人的博客写的代码,写的很简练,所以。。。。。。
革命尚未成功,自己还需努力!
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
while (n-- > 0) {
String s1 = sc.next();
String s2 = sc.next();
int k = sc.nextInt();
if (k >= 2) {
HashMap<Character, Integer> map0 = new HashMap<Character, Integer>();
fillWithZero(map0);
Statistics(map0, s1);
HashMap<Character, Integer> map1 = new HashMap<Character, Integer>();
fillWithZero(map1);
Statistics(map1, s2);
HashMap<Character, Integer> map2 = new HashMap<Character, Integer>();
while (k-- > 1) {
int num = 97;
for (int i = 0; i < 26; i++) {
char key = (char) num;
map2.put(key, map0.get(key) + map1.get(key));
num++;
}
map0.clear();
map0.putAll(map1);
map1.clear();
map1.putAll(map2);
}
print(map1);
} else {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
fillWithZero(map);
if (k == 0) {
Statistics(map, s1);
} else if (k == 1) {
Statistics(map, s2);
}
print(map);
}
System.out.println();
}
}
public static void fillWithZero(HashMap<Character, Integer> map) {//把集合中的每一个键的次数都列为一
int num = 97;
for (int i = 0; i < 26; i++) {
char C = (char) num;
map.put(C, 0);
num++;
}
}
public static void Statistics(HashMap<Character, Integer> map, String s) {//遍历字符串s,统计每一个字母出现的次数
for (int i = 0; i < s.length(); i++) {
if (map.containsKey(s.charAt(i))) {
map.put(s.charAt(i), map.get(s.charAt(i)) + 1);
}
}
}
/*本来想遍历双列集合,输出键和值,但是HashMap底层是由哈希算法实现的,不能保证怎么存就怎么取,也不能用Collections.sort();方法进行排序,所以就写了这样一个方法*/
public static void print(HashMap<Character, Integer> map) {//按示例的格式输出
int num = 97;
for (int i = 0; i < 26; i++) {
char key = (char) num;
System.out.println(key + ":" + map.get(key));
num++;
}
}
}