Decode the Message LeetCode solution in Java

1
class Solution {
2
public String decodeMessage(String key, String message) {
3
StringBuilder ans = new StringBuilder(); // Using String Builder to append the string
4
key = key.replaceAll(" ", "");
5
// Removing the spaces
6
HashMap<Character, Character> letters = new HashMap<>();
7
// Mapping the key into a hashmap.
8
char original = 'a';
9
for (int i = 0; i < key.length(); i++) {
10
if (!letters.containsKey(key.charAt(i))) {
11
letters.put(key.charAt(i), original++);
12
}
13
}
14
// After the first pass all the letters of the key will be mapped with their respective original
15
// letters.
16
for (int i = 0; i < message.length(); i++) {
17
if (letters.containsKey(message.charAt(i))) {
18
// Now replacing the letters of the message with appropriate letter according to the key
19
ans.append(letters.get(message.charAt(i)));
20
} else {
21
ans.append(message.charAt(i));
22
// This is for characters other than the letters in the key example a space " "
23
// They will not be replaced by any letters hence original letter is appended into the
24
// StringBuilder
25
}
26
}
27
return ans.toString();
28
}
29
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0