703472. Construct binary palindrome by repeated appending and trimming
Medium
Construct Binary Palindrome by Repeated Appending and Trimming
Summary
Construct a binary palindrome by repeatedly appending and trimming a given binary number. A binary palindrome is a binary string that reads the same forwards and backwards. The problem requires us to develop an algorithm to construct this binary palindrome.
Detailed Explanation
The approach to solve this problem involves a combination of DFS (Depth-First Search) and manipulation of binary strings. We start by creating a binary string from the given number. Then, we use DFS to append and trim the binary string until it becomes a palindrome.
Here's a step-by-step breakdown of the solution:
- Convert the given binary number into a binary string.
- Initialize an empty binary string
palindrometo store the constructed palindrome. - Start a DFS from the first character of the binary string, moving towards the end.
- For each character in the binary string, append it to
palindromeif it is equal to the corresponding character at the opposite end of the palindrome (i.e., the same position but on the other side). If not, trim the last character from the palindrome and move towards the center. - Continue this process until the DFS reaches the middle of the binary string or the entire string has been processed.
- The resulting
palindromeis the constructed binary palindrome.
Time Complexity: O(n), where n is the length of the input binary number.
Space Complexity: O(1), as we only use a constant amount of space to store the palindrome.
Optimized Solutions
Java
public class BinaryPalindrome {
public static String constructBinaryPalindrome(int n) {
StringBuilder palindrome = new StringBuilder();
String binaryStr = Integer.toBinaryString(n);
for (int i = 0; i < binaryStr.length(); i++) {
if (i == 0 || i == binaryStr.length() - 1) {
palindrome.append(binaryStr.charAt(i));
} else {
palindrome.append(binaryStr.charAt(i));
while (!palindrome.toString().equals(reverseString(palindrome.toString()))) {
palindrome.deleteCharAt(palindrome.length() - 1);
}
}
}
return palindrome.toString();
}
private static String reverseString(String s) {
StringBuilder sb = new StringBuilder(s).reverse();
return sb.toString();
}
}