Leetcode 214: Shortest Palindrome, leetcodepalindrome

Source: Internet
Author: User

Leetcode 214: Shortest Palindrome, leetcodepalindrome

Shortest PalindromeTotal Accepted: 172Total Submissions: 1344

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 using Ming this transformation.

For example:

Given"aacecaaa", Return"aaacecaaa".

Given"abcd", Return"dcbabcd".

[Idea]

Expand from a char to both sides (the characters on both sides are equal). If the string header can be extended all the time, add the remaining reverse at the end to the header of the original string.

Tips: 1. The Central Axis character starts from the middle, so that it is found to be the shortest. 2. The Central Axis character may be one or two.

[CODE]

public class Solution {    public String shortestPalindrome(String s) {    if(s.length()<=1 ) return s;        int center = (s.length()-1)/2;        String res="";        for(int i=center; i>=0; i--) {        if(s.charAt(i) == s.charAt(i+1)) {        if( (res = check1(s, i, i+1)) !=null) return res;        }    if( (res = check1(s, i, i)) !=null) return res;        }        return res;    }    //aabaac    private String check1(String s, int l, int r) {    int i=1;        for(; l-i>=0; i++) {            if(s.charAt(l-i) != s.charAt(r+i) ) break;        }                if(l-i>=0) return null;         StringBuilder sb = new StringBuilder(s.substring(r+i));        sb.reverse();        return sb+s;    }}


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.