-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathDecode the Message.java
28 lines (28 loc) · 1.31 KB
/
Decode the Message.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
// Runtime: 12 ms (Top 48.65%) | Memory: 44.7 MB (Top 35.73%)
class Solution {
public String decodeMessage(String key, String message) {
StringBuilder ans = new StringBuilder();//Using String Builder to append the string
key = key.replaceAll(" ", "");
//Removing the spaces
HashMap<Character,Character> letters = new HashMap<>();
//Mapping the key into a hashmap.
char original = 'a';
for (int i = 0; i < key.length() ; i++) {
if (!letters.containsKey(key.charAt(i))){
letters.put(key.charAt(i),original++);
}
}
//After the first pass all the letters of the key will be mapped with their respective original letters.
for (int i = 0; i < message.length(); i++) {
if (letters.containsKey(message.charAt(i))){
//Now replacing the letters of the message with appropriate letter according to the key
ans.append(letters.get(message.charAt(i)));
}else{
ans.append(message.charAt(i));
//This is for characters other than the letters in the key example a space " "
//They will not be replaced by any letters hence original letter is appended into the StringBuilder
}
}
return ans.toString();
}
}