Given a string s, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.
Example 1:
Input: "aacecaaa"
Output: "aaacecaaa"
Example 2:
Input: "abcd"
Output: "dcbabcd"
代码
Approach # Brute Force
Time complexity: O(n^2)
classSolution {publicStringshortestPalindrome(String s) {int n =s.length();String reversed =newStringBuilder(s).reverse().toString();int j =0;for (int i =0; i < n; i++) {if (s.substring(0, n-i) ==reversed.substring(i)) {returnresersed.substring(0, i) + s; } }return""; }}