Java for Leetcode 214 shortest palindrome

Source: Internet
Author: User

Given A string S, you is 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" .

Problem Solving Ideas:

The simplest way of thinking is to judge whether the substring is a palindrome string from the back to the front, and then to get the back of the former can be, but this can only grazing through the test, the most efficient of course is the KMP algorithm,

KMP can refer to Java for Leetcode 028 Implement strStr ()

Java implementation is as follows;

    Public String Shortestpalindrome (string s) {for        (int i=s.length (); i>=1;i--)        if (Ispalindrome (s.substring ( 0, I))        return new StringBuilder (s.substring (i)). reverse () +s;        Return "";    }    Static Boolean ispalindrome (String s) {    int left=0,right=s.length ()-1;    while (left<right)    if (S.charat (left++)!=s.charat (right--))    return false;    return true;    }

Java for Leetcode 214 shortest palindrome

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.