Given a string, find the shortest possible string which can be achieved by adding characters to the end of initial string to make it a palindrome.
Example
For st = "abcdc", the output should be buildPalindrome(st) = "abcdcba".
Input/Output
[execution time limit] 3 seconds (java)
[input] string st
A string consisting of lowercase English letters.
Guaranteed constraints: 3 ≤ st.length ≤ 10.
[output] string
[Java] Syntax Tips
// Prints help message to the console // Returns a string // // Globals declared here will cause a compilation error, // declare variables inside the function instead! String helloWorld(String name) { System.out.println("This prints to the console when you Run Tests"); return "Hello, " + name; }
String buildPalindrome(String s) {
for (int i = 0; i < s.length(); i++) {
if (isPalindrome(s.substring(i))) {
StringBuilder sb = new StringBuilder();
sb.append(s);
for (int j = i - 1; j >= 0; j--) {
sb.append(s.charAt(j));
}
return sb.toString();
}
}
// Guaranteed not to get here
//
return "";
}
boolean isPalindrome(String s) {
// Walk the string from head to tail
// comparing characters at each side as we go
//
int h = 0;
int t = s.length() - 1;
while (h < t) {
if (s.charAt(h) != s.charAt(t)) {
return false;
}
h++;
t--;
}
return true;
}