In: Computer Science
Given an original message, determine the cipher that will produce the encoded string that comes earliest alphabetically. Return this encoded string. In the example below, the second cipher produces the alphabetically earliest encoded string ("abccd").
For example, if John's message is "hello" and his cipher maps 'h' to 'd', 'e' to 'i', 'l' to 'p' and 'o' to 'y', the encoded message will be "dippy". If the cipher maps 'h' to 'a', 'e' to 'b', 'l' to 'c' and 'o' to 'd', then the encoded message will be "abccd".
My code (bolded code is part of the question and cannot be changed):
string encrypt(string message){
// you write code here
string unEncryp;
for(int i = 0; i < message.length()){
char temp = message[i];
switch(temp){
default:
break;
}
}
return unEncryp;
}
Please follow the code and comments for description :
CODE :
import java.util.HashMap; // required imports
import java.util.Map;
public class Cipher // class to run the code
{
public static String encrypt(String message) // method that
encrypts the string as desired
{
char charData = 'a'; // character starts
StringBuilder sb = new StringBuilder(); // string builder
object
Map<Character, Character> msgData = new HashMap<>(); //
map that stores the characters
for (Character c : message.toCharArray()) // iterate over the
map
{
if (!msgData.containsKey(c)) // check for the match character
{
sb.append(charData); // append the data
msgData.put(c, charData);
++charData;
} else
{
sb.append(msgData.get(c));
}
}
return sb.toString(); // return the string
}
public static void main(String[] args) // driver method
{
String message = "hello";
System.out.println("The Input String is : " + message);
System.out.println("The Result String is : " +
encrypt(message));
}
}
OUTPUT :

Hope this is helpful.