714262. String Mirror
Easy
Here is the Markdown blog post for the "String Mirror" problem:
String Mirror
Summary
The String Mirror problem involves creating a new string that is the mirror reflection of the input string. The task is to create an algorithm that takes a given string as input and returns the mirrored version of the string. This problem requires understanding of basic string manipulation techniques.
Detailed Explanation
To solve this problem, we can use a simple approach where we iterate over the input string from both ends (start and end) and construct the mirrored string.
Here's a step-by-step breakdown of the solution:
- Initialize an empty string
mirrored_strto store the result. - Iterate over the input string
strfrom both ends (start and end). - For each character at position
i, add the corresponding character at positionn-i-1(wherenis the length of the input string) tomirrored_str. This ensures that characters are mirrored correctly. - Continue this process until you reach the middle of the input string (or the beginning of the end, depending on whether the input string has an even or odd length).
- Return the constructed
mirrored_stras the result.
Time complexity: O(n), where n is the length of the input string. Space complexity: O(n), since we need to store the mirrored string.
Optimized Solutions
Java
public String stringMirror(String str) {
StringBuilder mirroredStr = new StringBuilder();
int n = str.length();
for (int i = 0; i < n / 2; i++) {
mirroredStr.append(str.charAt(n - i - 1));
if (i != n / 2) {
mirroredStr.append(str.charAt(i));
}
}
return mirroredStr.toString();
}