1. Title
Shortest Palindrome
2. Http address
https://leetcode.com/problems/shortest-palindrome/
3. The question
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.
For example:
Given "aacecaaa"
, return "aaacecaaa"
.
Given "abcd"
, return "dcbabcd"
.
4. My code (AC)
1 //Accepted 2 public String shortestPalindrome0(String s) { 3 if( s == null || s.length() <= 1 || this.isPalindrom(s)) 4 { 5 return s; 6 } 7 int len = s.length(); 8 int mid = len /2; 9 for(int i = mid; i >= 0; i--) 10 { 11 StringBuilder sb = new StringBuilder(""); 12 if(checkIsPalindrom(s,i,sb)) 13 { 14 // int dis = (len-i) - (i); 15 //System.out.println("outer" + sb.toString()); 16 int index = Integer.parseInt(sb.toString()); 17 18 StringBuilder strB = new StringBuilder(s.substring(index)); 19 return strB.reverse().toString() + s; 20 } 21 } 22 return "error"; 23 } 24 // 25 private boolean checkIsPalindrom(String s, int mid, StringBuilder sb) { 26 // TODO Auto-generated method stub 27 int len = s.length(); 28 int i = mid - 1; 29 int j = mid; 30 if( mid < 1){ 31 sb.append(1); 32 return true; 33 } 34 35 36 while( j < len && i >= 0) 37 { 38 if(s.charAt(j) != s.charAt(i)) 39 { 40 break; 41 } 42 j++; 43 i--; 44 } 45 46 if( j < len && i >= 0) 47 { 48 i = mid - 1; 49 j = mid + 1; 50 if( j >= len) 51 { 52 return false; 53 } 54 while( j < len && i >= 0) 55 { 56 if(s.charAt(j) != s.charAt(i)) 57 { 58 return false; 59 } 60 j++; 61 i--; 62 } 63 } 64 65 sb.append(j); 66 return true; 67 } 68 69 public boolean isPalindrom(String s){ 70 if( s == null || s.length() <= 1) 71 return true; 72 int len = s.length(); 73 int i = 0; 74 int j = len -1; 75 while( i < j) 76 { 77 if( s.charAt(i) != s.charAt(j)){ 78 return false; 79 } 80 i++; 81 j--; 82 } 83 return true; 84 }