-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathEncrypt and Decrypt Strings.java
37 lines (30 loc) · 1.06 KB
/
Encrypt and Decrypt Strings.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Encrypter {
Map<String, Integer> encryptedDictCount;
int[] keys;
Set<String> dictionary;
String[] val;
public Encrypter(char[] keys, String[] values, String[] dictionary) {
this.keys = new int[26];
encryptedDictCount = new HashMap<>();
this.val = values.clone();
this.dictionary = new HashSet<>(Arrays.asList(dictionary));
for(int i=0; i<keys.length; i++) {
this.keys[keys[i] - 'a'] = i;
}
for(String dict : dictionary) {
String encrpted = encrypt(dict);
encryptedDictCount.put(encrpted, encryptedDictCount.getOrDefault(encrpted, 0) + 1);
}
}
public String encrypt(String word1) {
StringBuilder sb = new StringBuilder();
for(int i =0; i < word1.length(); i++) {
int c = word1.charAt(i) - 'a';
sb.append(val[keys[c]]);
}
return sb.toString();
}
public int decrypt(String word2) {
return encryptedDictCount.getOrDefault(word2, 0);
}
}