The title

Given a string s, you can convert it to a palindrome string by preadding characters to the string. Find and return the shortest palindrome string that can be converted in this way.

Example 1:

Input:"aacecaaa"Output:"aaacecaaa"
Copy the code

Example 2:

Input:"abcd"Output:"dcbabcd"
Copy the code

code

Class Solution {/** * Created by swort. * @desc generates a palindrome string * @param$s
     * @return string
     */
    function shortest_palindrome($s)
    {
        $temp = ' ';
        $len  = strlen($s);
        if ($len > 1) {
            if (!$this->is_palindrome($s)) {
                for ($i = 0; $i < $len - 1; $i++) {// Take one subscript string at a time from the tail to the front$temp = $temp . $s[$len - 1 - $i];
                    if ($this->is_palindrome($temp . $s)) {
                        return $temp . $s; }}}}return $s; } /** * Created by tartar. * @desc check whether it is a palindrome string * @param$string
     * @return bool
     */
    function is_palindrome($string)
    {
        $len    = strlen($string);
        $is_odd = ($len% 2 == 0)? 0:1;$midd   = $len/ 2; // Take the first few digits of the string, starting at position 0$f_string = substr($string, 0, $midd); // From the end of the last cut (odd + 1), cut the last few digits of the string and invert the string$b_string = strrev(substr($string.$midd + $is_odd.$midd));
        if ($f_string! =$b_string) {
            return false;
        }
        return true; }}Copy the code

The results of

Submission result: The submission is successful

Pass test case: 120/120

Language: PHP

Execution time: 632 ms

Memory consumption: 15.3 MB