简体   繁体   English

Java:如何通过插入最少数量的字符来创建字符串的最短回文?

[英]Java: How to create the shortest palindrome of a string by inserting the minimum number of characters?

I currently have the following implementation that handles finding the shortest palindrome with a given string by inserting the minimum number of characters, but only handling character insertions at the front to create the shortest palindrome. 我目前有以下实现,该实现通过插入最少数量的字符来查找给定字符串中最短的回文,但是仅在最前面处理字符插入以创建最短的回文。

But with the following implementation or if there's any better out there, how can I do so where the characters can be inserted at any point(s) in the string to make it a palindrome? 但是,通过以下实现或者如果还有更好的实现,我该如何在可将字符插入字符串的任何点以使其成为回文的情况下做到这一点?

Will accept and upvote the answer. 将接受并支持答案。 Thank you 谢谢

public class Answer {
    public String findShortestPalindrome(String s) {
        int len = s.length();
        if (len <= 1) {
            return s;
        }
        int i = len - 1;
        for (; i >= 0; --i) {
            if (stringIsPalindrome(s, 0, i)) {
                break;
            }
        }

        StringBuilder sb = new StringBuilder(s.substring(i + 1));
        sb.reverse().append(s);
        return sb.toString();
    }

    public boolean stringIsPalindrome(String s, int start, int end) {
        while (start < end) {
            if (s.charAt(start) != s.charAt(end)) {
                return false;
            }
            start++;
            end--;
        }
        return true;
    }
}

DIFFERENCE Looking for shortest palindrome that handles insertion in any point in the string. 差异寻找可处理字符串中任何点插入的最短回文。

You could try this solution. 您可以尝试此解决方案。 This should works! 这应该工作!

public boolean stringIsPalindrome(String s, int start, int end) {

    String str1 = s.substring(0,Math.floor((end-start)/2));
    String str2 = s.substring(Math.floor((end-start)/2),end);
    str2 = reverseString(str2);
    return str1.equals(str2);
}

public String reverseString(String s) {
            //YOUR REVERSE STRING METHOD
    }

You can implement the following kinda brute force algorithm: 您可以实现以下种类的蛮力算法:

  1. If the input string is empty or consists of one element return the input 如果输入字符串为空或包含一个元素,则返回输入
  2. If first character of the string equals last one then apply the procedure to the input string without first and last items 如果字符串的第一个字符等于最后一个字符,则对输入的字符串应用此过程,而不使用第一个和最后一个项目
  3. If first is not the same with last then you have two options: 如果first与last不相同,则有两个选择:

     left = last + palindromed(input without last) + last or right = first + palindromed(input without first) + first 

    so on this step you select the shortest solution 因此,在此步骤中,您选择最短的解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM