解法一:逆向思维
关键点
1.字符串A经加密后只会有一种结果,字符串B解密会有多种结果
2.所以直接将dictionary
中的字符串加密得到一个结果集<加密后的字符串,出现次数>
3.将输入的字符串去结果集中获取value值即可
class Encrypter {
Map<Character, String> map = new HashMap<>();
Map<String, Integer> res = new HashMap<>();
public Encrypter(char[] keys, String[] values, String[] dictionary) {
for (int i = 0; i < keys.length; i++) {
map.put(keys[i], values[i]);
}
for (String s : dictionary) {
String enS = encrypt(s);
res.put(enS,res.getOrDefault(enS,0) + 1);
}
}
public String encrypt(String word1) {
char[] chars = word1.toCharArray();
String s = "";
for (char aChar : chars) {
s += map.get(aChar);
}
return s;
}
public int decrypt(String word2) {
return res.getOrDefault(word2,0);
}
}
解法二:笨比方法,暴力就完事了
根据题意,加密
根据题意,解密
然后就超时了,不愧是我,总是能写出复杂且低效的代码
class Encrypter {
Map<Character, String> map = new HashMap<>();
List<String> dic;
Set<String> combine = new HashSet<>();
public Encrypter(char[] keys, String[] values, String[] dictionary) {
for (int i = 0; i < keys.length; i++) {
map.put(keys[i], values[i]);
}
dic = Arrays.asList(dictionary);
}
public String encrypt(String word1) {
char[] s = word1.toCharArray();
String res = "";
for (char c : s) {
res += map.get(c);
}
return res;
}
public int decrypt(String word2) {
combine.clear();
char[] c = word2.toCharArray();
int count = 0;
bfs(c, 0, "", c.length/2);
for (String s : combine) {
if (dic.contains(s)) {
count++;
}
}
return count;
}
public void bfs(char[] c, int i ,String string, int size) {
if (string.length() == size) {
combine.add(string);
}
for (int j = i; j < c.length; j = j + 2) {
String s = "" + c[j] + c[j + 1];
for (Character character : map.keySet()) {
if (map.get(character).equals(s)) {
bfs(c, j + 2, string + character, size);
}
}
}
}
}