如何找到最长的回文(java)

时间:2012-08-27 05:25:52

标签: java string joptionpane palindrome

您好我一直在做这个java程序,我应该输入一个字符串并输出可以找到的最长的回文。 但我的程序只输出最长回文的第一个字母..我非常需要你的帮助..谢谢!

应该是:

INPUT:abcdcbbcdeedcba 输出:bcdeedcb 有两个回文串:bcdcb和bcdeedcb

但是当我输入时:abcdcbbcdeedcba 输出:b

import javax.swing.JOptionPane;
public class Palindrome5
{   public static void main(String args[])
    {   String word = JOptionPane.showInputDialog(null, "Input String : ", "INPUT", JOptionPane.QUESTION_MESSAGE);
        String subword = "";
        String revword = "";
        String Out = "";
        int size = word.length();
        boolean c;

        for(int x=0; x<size; x++)
        {   for(int y=x+1; y<size-x; y++)
            {   subword = word.substring(x,y);
                c = comparisonOfreverseword(subword);
                if(c==true)
                {
                    Out = GetLongest(subword);
                }
            }
        }
        JOptionPane.showMessageDialog(null, "Longest Palindrome : " + Out, "OUTPUT", JOptionPane.PLAIN_MESSAGE);
    }

    public static boolean comparisonOfreverseword(String a)
        {   String rev = "";
            int tempo = a.length();
            boolean z=false;
            for(int i = tempo-1; i>=0; i--)
            {
                char let = a.charAt(i);
                rev = rev + let;
            }
            if(a.equalsIgnoreCase(rev))
            {
                z=true;
            }
            return(z);
        }
    public static String GetLongest(String sWord)
        {
            int sLength = sWord.length();
            String Lpalindrome = "";
            int storage = 0;
            if(storage<sLength)
            { 
                storage = sLength;

                Lpalindrome = sWord;
            }
            return(Lpalindrome);
        }
}

6 个答案:

答案 0 :(得分:1)

修改程序..该程序将提供正确的输出

package pract1;

import javax.swing.JOptionPane;
public class Palindrome5
{

    public static void main(String args[])
    {



    String word = JOptionPane.showInputDialog(null, "Input String : ", "INPUT", JOptionPane.QUESTION_MESSAGE);
    String subword = "";
    String revword = "";
    String Out = "";

    int size = word.length();
    boolean c;
        String Lpalindrome = "";
        int  storage=0;

  String out="";

    for(int x=0; x<size; x++)
    {   for(int y=x+1; y<=size; y++)
        {   subword = word.substring(x,y);
            c = comparisonOfreverseword(subword);
            if(c==true)
            {
                 int sLength = subword.length();


                   if(storage<sLength)
                 { 
                     storage = sLength;

                     Lpalindrome = subword;
                     out=Lpalindrome;


                 }

            }
        }
    }
            JOptionPane.showMessageDialog(null, "Longest Palindrome : " + out, "OUTPUT", JOptionPane.PLAIN_MESSAGE);
}

public static boolean comparisonOfreverseword(String a)
    {   String rev = "";
        int tempo = a.length();
        boolean z=false;
        for(int i = tempo-1; i>=0; i--)
        {
            char let = a.charAt(i);
            rev = rev + let;
        }
        if(a.equalsIgnoreCase(rev))
        {
            z=true;
        }
        return(z);
    }


}

答案 1 :(得分:0)

你有两个错误:

1

for(int y=x+1; y<size-x; y++)

应该是

for(int y=x+1; y<size; y++)

因为你仍然希望一直走到字符串的末尾。使用前一个循环,因为x在整个循环中增加,所以子串大小会在整个循环中减少(通过从末尾删除x个字符)。

2

您没有存储到目前为止找到的最长的字符串或其长度。代码

int storage = 0;
if(storage<sLength) { 
    storage = sLength;
    ...

说'如果新字符串长于零个字符,那么我将假设它是迄今为止找到的最长字符串并将其作为LPalindrome返回'。这没有任何帮助,因为我们之前可能已经找到了更长的回文。

如果是我,我会制作一个静态变量(例如longestSoFar)来保持到目前为止找到的最长的回文(最初是空的)。对于每个新的回文,检查新的回文是否长于最长的时间。如果更长,则将其分配给longestSoFar。然后在最后,显示longestSoFar。

一般情况下,如果你在程序中“记住”某些内容时遇到问题(例如以前看过的值),你必须考虑静态存储一些内容,因为一旦方法完成就会忘记局部变量。

答案 2 :(得分:0)

公共类LongestPalindrome {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
String S= "abcdcba";
printLongestPalindrome(S);
}


public static void printLongestPalindrome(String S)
{
    int maxBack=-1;
    int maxFront = -1;
    int maxLength=0;
    for (int potentialCenter = 0 ; potentialCenter < S.length();potentialCenter ++ )
    {   
        int back = potentialCenter-1;
        int front = potentialCenter + 1;
        int longestPalindrome = 0;
        while(back >=0 && front<S.length() && S.charAt(back)==S.charAt(front))
        {
            back--;
            front++;
            longestPalindrome++;

        }
        if (longestPalindrome > maxLength)
        {
            maxLength = longestPalindrome+1;
            maxBack = back + 1;
            maxFront = front;
        }
        back = potentialCenter;
        front = potentialCenter + 1;
        longestPalindrome=0;
        while(back >=0 && front<S.length() && S.charAt(back)==S.charAt(front))
        {
            back--;
            front++;
            longestPalindrome++;
        }
        if (longestPalindrome > maxLength)
        {
            maxLength = longestPalindrome;
            maxBack = back + 1;
            maxFront = front;
        }

    }


    if (maxLength == 0) System.out.println("There is no Palindrome in the given String");
    else{
        System.out.println("The Longest Palindrome is " + S.substring(maxBack,maxFront) + "of " + maxLength);
    }
}

}

答案 3 :(得分:0)

我有自己的方法以随机单词获得最长回文。检查一下

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);

System.out.println(longestPalSubstr(in.nextLine().toLowerCase()));


}




static String longestPalSubstr(String str) {

       char [] input = str.toCharArray();
       Set<CharSequence> out = new HashSet<CharSequence>();

      int n1 = str.length()-1;


      for(int a=0;a<=n1;a++)
       {
          for(int m=n1;m>a;m--)
          {

          if(input[a]==input[m])
          {

           String nw = "",nw2="";

           for (int y=a;y<=m;y++)
           {

                nw=nw+input[y];
           }
           for (int t=m;t>=a;t--)
           {

               nw2=nw2+input[t];
           }


           if(nw2.equals(nw))
           {

                out.add(nw);


               break;
           }
       }

     }

   }


    int a = out.size();
    int maxpos=0;
    int max=0;
    Object [] s = out.toArray();

    for(int q=0;q<a;q++)
    {

        if(max<s[q].toString().length())
        {
            max=s[q].toString().length();
            maxpos=q;
        }
    }


   String output = "longest palindrome is : "+s[maxpos].toString()+" and the lengths is : "+ max; 
   return output;



}

此方法将返回最大长度回文及其长度。这是我尝试并获得答案的一种方式。并且此方法无论其是奇数长度还是偶数长度都将运行。

答案 4 :(得分:0)

这是我获得最长回文的方法。这将返回长度和回文词

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);

System.out.println(longestPalSubstr(in.nextLine().toLowerCase()));


}




static String longestPalSubstr(String str) {

       char [] input = str.toCharArray();
       Set<CharSequence> out = new HashSet<CharSequence>();

      int n1 = str.length()-1;


      for(int a=0;a<=n1;a++)
       {
          for(int m=n1;m>a;m--)
          {

          if(input[a]==input[m])
          {

           String nw = "",nw2="";

           for (int y=a;y<=m;y++)
           {

                nw=nw+input[y];
           }
           for (int t=m;t>=a;t--)
           {

               nw2=nw2+input[t];
           }


           if(nw2.equals(nw))
           {

                out.add(nw);


               break;
           }
       }

     }

   }


    int a = out.size();
    int maxpos=0;
    int max=0;
    Object [] s = out.toArray();

    for(int q=0;q<a;q++)
    {

        if(max<s[q].toString().length())
        {
            max=s[q].toString().length();
            maxpos=q;
        }
    }


   String output = "longest palindrome is : "+s[maxpos].toString()+" and the lengths is : "+ max; 
   return output;



}

此方法将返回最大长度回文及其长度。这是我尝试并获得答案的一种方式。并且此方法无论其是奇数长度还是偶数长度都将运行。

答案 5 :(得分:0)

public class LongestPalindrome {

    public static void main(String[] args) {
        HashMap<String, Integer> result = findLongestPalindrome("ayrgabcdeedcbaghihg123444456776");
        result.forEach((k, v) -> System.out.println("String:" + k + " Value:" + v));
    }


    private static HashMap<String, Integer> findLongestPalindrome(String str) {
        int i = 0;
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        while (i < str.length()) {
            String alpha = String.valueOf(str.charAt(i));
            if (str.indexOf(str.charAt(i)) != str.lastIndexOf(str.charAt(i))) {
                String pali = str.substring(i, str.lastIndexOf(str.charAt(i)) + 1);
                if (isPalindrome(pali)) {
                    map.put(pali, pali.length());
                    i = str.lastIndexOf(str.charAt(i));
                }
            }
            i++;
        }
        return map;
    }

    public static boolean isPalindrome(String input) {
        for (int i = 0; i <= input.length() / 2; i++) {
            if (input.charAt(i) != input.charAt(input.length() - 1 - i)) {
                return false;
            }
        }
        return true;

    }

}

这种方法很简单。

输出:
字符串:abcdeedcba值:10
字符串:4444值:4
字符串:6776值:4
字符串:ghihg值:5