1. import java.util.HashMap;
  2. import java.util.Map;
  3. class StringDecoder {
  4. private Map<String, String> decodingMap; // Stores the mapping of encoded characters to original characters
  5. public StringDecoder(Map<String, String> decodingMap) {
  6. this.decodingMap = new HashMap<>(decodingMap); // Create a copy to avoid modifying the original map
  7. }
  8. public String decode(String encodedString) {
  9. StringBuilder decodedString = new StringBuilder();
  10. int i = 0;
  11. while (i < encodedString.length()) {
  12. String current = encodedString.substring(i, i + 1); // Extract a single character
  13. if (decodingMap.containsKey(current)) {
  14. decodedString.append(decodingMap.get(current)); // Append the decoded character
  15. i++;
  16. } else {
  17. i++; // Skip the character if it's not in the map
  18. }
  19. }
  20. return decodedString.toString();
  21. }
  22. public static void main(String[] args) {
  23. //Example Usage
  24. Map<String, String> decodingMap = new HashMap<>();
  25. decodingMap.put("A", "X");
  26. decodingMap.put("B", "Y");
  27. decodingMap.put("C", "Z");
  28. StringDecoder decoder = new StringDecoder(decodingMap);
  29. String encodedString = "ABC";
  30. String decodedString = decoder.decode(encodedString);
  31. System.out.println("Encoded: " + encodedString);
  32. System.out.println("Decoded: " + decodedString);
  33. }
  34. }

Add your comment