import java.util.HashMap;
import java.util.Map;
class StringDecoder {
private Map<String, String> decodingMap; // Stores the mapping of encoded characters to original characters
public StringDecoder(Map<String, String> decodingMap) {
this.decodingMap = new HashMap<>(decodingMap); // Create a copy to avoid modifying the original map
}
public String decode(String encodedString) {
StringBuilder decodedString = new StringBuilder();
int i = 0;
while (i < encodedString.length()) {
String current = encodedString.substring(i, i + 1); // Extract a single character
if (decodingMap.containsKey(current)) {
decodedString.append(decodingMap.get(current)); // Append the decoded character
i++;
} else {
i++; // Skip the character if it's not in the map
}
}
return decodedString.toString();
}
public static void main(String[] args) {
//Example Usage
Map<String, String> decodingMap = new HashMap<>();
decodingMap.put("A", "X");
decodingMap.put("B", "Y");
decodingMap.put("C", "Z");
StringDecoder decoder = new StringDecoder(decodingMap);
String encodedString = "ABC";
String decodedString = decoder.decode(encodedString);
System.out.println("Encoded: " + encodedString);
System.out.println("Decoded: " + decodedString);
}
}
Add your comment