简体   繁体   English

在Java中将字符串转换为回文

[英]Converting a string into a palindrome in Java

I'm trying to find the shortest palindrome that one can create from S by by adding 0 or more characters in front of it.我试图通过在 S 前面添加 0 个或多个字符来找到可以从 S 创建的最短回文。 For example the shortest palindrome can be constructed from 'baaa' is 'aaabaaa'.例如,可以从 'baaa' 构造出的最短回文是 'aaabaaa'。 The two functions that I'm using are given below.下面给出了我正在使用的两个函数。 This works for this case for doesn't yield the shortest result in all cases.这适用于这种情况,因为在所有情况下都不会产生最短的结果。

public static boolean checkPalindrome(String s){

        for (int i = 0; i < s.length()/2; i++) {
            if (s.charAt(i) != s.charAt(s.length() - i - 1)) return false;
        }

        return true;

    }

    public static int makePalindrome(String s){
    int min = 0;
    StringBuilder str = new StringBuilder(s);
    for (int i = 1; i < s.length() ; i++) {
        str.insert(0, s.charAt(i));
        if (checkPalindrome(str.toString()) == true) {
            min = str.length();
            break;
        }

    }
    return min;
}

I can't seem to figure out what logical step am I missing.我似乎无法弄清楚我错过了什么合乎逻辑的步骤。

Your helper method checkPalindrome seems correct.您的辅助方法checkPalindrome似乎是正确的。 Your thinking is also correct (append characters until the result is a palindrome), but the way you're going about it is wrong.您的想法也是正确的(追加字符直到结果为回文),但是您的处理方式是错误的。

To reiterate: Our logic is, while our result is not a palindrome, take the next character from the end (moving towards the start of the string) and append it to the prefix.重申:我们的逻辑是,虽然我们的结果不是回文,但从末尾(向字符串的开头移动)取下一个字符并将其附加到前缀。 So for the string "abcd" , we would try所以对于字符串"abcd" ,我们会尝试

  • "" + "abcd" -> "abcd" -> false "" + "abcd" -> "abcd" -> 假
  • "d" + "abcd" -> "dabcd" -> false "d" + "abcd" -> "dabcd" -> 假
  • "dc" + "abcd" -> "dcabcd" -> false "dc" + "abcd" -> "dcabcd" -> 假
  • "dcb" + "abcd" -> "dcbabcd" -> true, terminate "dcb" + "abcd" -> "dcbabcd" -> 真,终止

Here's a fixed version:这是一个固定版本:

public static String makePalindrome(String base){
    String pref = "";
    int i = base.length() - 1;
    while(! checkPalindrome(pref + base)){
        pref = pref + base.charAt(i);
        i --;
    }
    return pref + base;
}

IDEONE: http://ideone.com/tawjmG IDEONE: http ://ideone.com/tawjmG

We can find the shortest Palindrome using the following logic:我们可以使用以下逻辑找到最短的回文:

Find the midpoint, loop from 0 to midpoint, length-1 to midpoint.找到中点,从 0 到中点循环,length-1 到中点。

If palindrome, return如果是回文,则返回

If not palindrome, add 1 to midpoint, do same logic如果不是回文,在中点加1,做同样的逻辑

In code:在代码中:

static String shortestPalindrome(String s) {
    if (s.length() == 1) return s;
    return recShortestPalindrome(s, s.length()>>1, 0);
}

static String recShortestPalindrome(String s, int mid, int add) {
    // AABBA[X]
    int fakeLen = s.length() + add;
    for (int i = 0; i < mid; i++) {
        char c1 = s.charAt(i);
        int p1 = fakeLen - 1 - i;

        if (p1 < s.length()) {
            char c2 = s.charAt(p1);

            if (c2 != c1) {
                return recShortestPalindrome(s, mid+1, add+1);
            }
        }
    }

    // found a pattern that works
    String h1 = s.substring(0, mid);
    String h2 = new StringBuilder(h1).reverse().toString();

    String ret = h1+h2;

    int midPoint = ret.length()/2;

    if (ret.length()%2 == 0 && ret.length() >= 2) {
        char c1 = ret.charAt(midPoint);
        char c2 = ret.charAt(midPoint-1);

        if (c1 == c2) {
            return ret.substring(0, midPoint) + ret.substring(midPoint+1, ret.length());
        }
    }

    return h1+h2;
}

I am not sure i understand the question but from what i understood you want to turn Strings like Hello to olleHello To do this, loop trhough each char of the string with like:我不确定我是否理解这个问题,但根据我的理解,您想将像Hello这样的字符串转换为olleHello要做到这一点,请使用如下循环遍历字符串的每个字符:

    String example = "Hello There Mate"; //our string
    StringBuilder exampleBuilder = new StringBuilder();
    for(int i=example.length()-1; i>0; i--)
        exampleBuilder.append(example.charAt(i));
    //Our loop, the reason why it is example.lenght-1
    //is because we want the first letter to appear only
    //1 time :)
    String finalString = exampleBuilder.toString()+example;
    //The final string, should be 'olleHello'
    System.out.println(finalString);

Hope thats what you are looking for :D希望这就是你要找的:D

Python Solution:蟒蛇解决方案:

def isPalindrome(x):
    if x == "":
        return False

    r = ""
    r = str(x)
    r = r[::-1]

    return True if x == r else False

def makePalindrome(my_str):

    pref = ""
    i = len(my_str) - 1

    while isPalindrome(pref + my_str) == False:
        pref = pref + my_str[i]
        i -= 1

    return pref + my_str







my_str = "abcd"
print(makePalindrome(my_str))

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

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