|
| 1 | +package string; |
| 2 | + |
| 3 | +/** |
| 4 | + * Created by gouthamvidyapradhan on 21/07/2018. |
| 5 | + * |
| 6 | + * Given a string s, you are allowed to convert it to a palindrome by adding characters in front of it. Find and |
| 7 | + * return the shortest palindrome you can find by performing this transformation. |
| 8 | +
|
| 9 | + Example 1: |
| 10 | +
|
| 11 | + Input: "aacecaaa" |
| 12 | + Output: "aaacecaaa" |
| 13 | + Example 2: |
| 14 | +
|
| 15 | + Input: "abcd" |
| 16 | + Output: "dcbabcd" |
| 17 | +
|
| 18 | + Solution: O(N ^ 2): for i : (s.length() - 1 -> 0) check if (0, i) is a paliandrome, if not append char at i to |
| 19 | + result string else return string (result + (0, i)) |
| 20 | + */ |
| 21 | +public class ShortestPalindrome { |
| 22 | + |
| 23 | + /** |
| 24 | + * Main method |
| 25 | + * @param args |
| 26 | + * @throws Exception |
| 27 | + */ |
| 28 | + public static void main(String[] args) throws Exception{ |
| 29 | + System.out.println(new ShortestPalindrome().shortestPalindrome("aaaaaaaaaa")); |
| 30 | + } |
| 31 | + |
| 32 | + public String shortestPalindrome(String s) { |
| 33 | + if(s.length() == 0 || s.length() == 1){ |
| 34 | + return s; |
| 35 | + } else if(s.length() == 2){ |
| 36 | + if(s.charAt(0) == s.charAt(1)){ |
| 37 | + return s; |
| 38 | + } else{ |
| 39 | + return (s.charAt(1) + s); |
| 40 | + } |
| 41 | + } |
| 42 | + if(isPaliandrome(s, 0, s.length() - 1)) return s; |
| 43 | + StringBuilder sb = new StringBuilder(""); |
| 44 | + for(int i = 0, j = s.length() - 1; j >= i; j--){ |
| 45 | + if(!isPaliandrome(s, i, j)){ |
| 46 | + sb.append(s.charAt(j)); |
| 47 | + } else{ |
| 48 | + sb.append(s.substring(0, s.length())); |
| 49 | + break; |
| 50 | + } |
| 51 | + } |
| 52 | + return sb.toString(); |
| 53 | + } |
| 54 | + |
| 55 | + boolean isPaliandrome(String s, int x, int y){ |
| 56 | + for(int i = x, j = y; i < j; i++, j--){ |
| 57 | + if(s.charAt(i) != s.charAt(j)) return false; |
| 58 | + } |
| 59 | + return true; |
| 60 | + } |
| 61 | +} |
0 commit comments