leetcode ShortestPalindrome
z
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class ShortestPalindrome {
/**
* 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"
*/
public static void main(String[] args){
String[] test = {"hello", "aaa", "a", "de"};
for (String s: test){
// System.out.println(isPalidrome(s));
System.out.println(shortestPalindrome(s));
}
}
public static String shortestPalindrome(String s) {
if (isPalidrome(s))
return s;
s = new StringBuffer(s).reverse().toString();
String ss = s;
int length = 1;
while(!isPalidrome(ss)){
ss = s + new StringBuffer(s.substring(0, length)).reverse().toString();
length ++;
}
return ss;
}

public static boolean isPalidrome(String s){
char[] l = s.toCharArray();
if (l.length == 1 || (l.length == 2 && l[0] == l[1])){
return true;
}
else if (l.length > 2 && isPalidrome(s.substring(1, s.length()-1)) && l[0] == l[l.length-1]){
return true;
}
else{
return false;
}
}
}