875952. Encode and Decode Strings
Encode and Decode Strings
Slug: encode-and-decode-strings
Difficulty: Medium
Id: 875952
Topic Tags: Strings, Arrays
Company Tags: None
Summary
Given a string s and an integer n, we need to perform two operations:
- Encode: Replace each character in the string with its ASCII value multiplied by
n. - Decode: Reverse the encoding process.
This problem requires a basic understanding of strings, arrays, and mathematical operations.
Detailed Explanation
To solve this problem, we will create two separate functions: one for encoding and another for decoding.
Encoding Function
The encoding function takes the input string s and integer n as parameters. It iterates through each character in the string, multiplies its ASCII value by n, and stores the result in a new array or string.
Here's the step-by-step breakdown:
- Create an empty array or string to store the encoded values.
- Iterate through each character in the input string using a loop (e.g., for-each or while-loop).
- For each character, multiply its ASCII value by
nand add the result to the new array or string. - Return the encoded array or string.
Decoding Function
The decoding function takes the encoded array or string and integer n as parameters. It iterates through each element in the encoded array or string, divides its value by n, and stores the result in a new array or string.
Here's the step-by-step breakdown:
- Create an empty array or string to store the decoded values.
- Iterate through each element in the encoded array or string using a loop (e.g., for-each or while-loop).
- For each element, divide its value by
nand add the result to the new array or string. - Return the decoded array or string.
Time Complexity Analysis The time complexity of both encoding and decoding functions is O(n), where n is the length of the input string. This is because we are iterating through each character in the string once.
Space Complexity Analysis The space complexity of both encoding and decoding functions is also O(n), as we are creating a new array or string to store the encoded or decoded values.
Optimized Solutions
Java
public class EncodeDecode {
public static String encode(String s, int n) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
sb.append((int) c * n);
}
return sb.toString();
}
public static String decode(String s, int n) {
StringBuilder sb = new StringBuilder();
for (String str : s.split("")) {
sb.append((char) Integer.parseInt(str) / n);
}
return sb.toString();
}
}