Java 查找字符串中的所有回文

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22075224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:25:46  来源:igfitidea点击:

find all palindromes in string

javaloopspalindrome

提问by kealtuve

I need to find all the palindromes in a string. It takes user input

我需要在一个字符串中找到所有的回文。它需要用户输入

example:"abbaalla"

例如:“阿巴拉”

it loops through creating a substring that changes as the loop progresses.

它循环创建一个随着循环进行而改变的子字符串。

example: checks palindrome "a" (true) "ab"(false) "abb" (false) "abba" (true) and so on..

例如:检查回文“a”(真)“ab”(假)“abb”(假)“abba”(真)等等。

once it reaches the max length of the word it iterates the start of the substring and repeats

一旦达到单词的最大长度,它就会迭代子字符串的开头并重复

example: check palindrome "b" "bb" "bba" and so on..

例如:检查回文“b”“bb”“bba”等等..

I need to change the code so that once it finds the first largest palindrome ("abba") the start of the loop will take place after that substring. so the next palindrome should read "alla"

我需要更改代码,以便一旦找到第一个最大的回文(“abba”),循环的开始将在该子字符串之后进行。所以下一个回文应该是“alla”

the final output should be a string that includes all palindromes. in this case;

最终输出应该是一个包含所有回文的字符串。在这种情况下;

output: "abba alla"

输出:“阿爸阿拉”

Also this program currently results in: String index out of range: -1

该程序当前还导致:字符串索引超出范围:-1

 public static String findAllPalindromes(String input){
     int indexStart = 0;
     int wordMax = input.length();
     int wordLength;
     String checkPalindrome;
     String allPalindromes = "";
     for (wordLength = 2; wordLength <= wordMax; wordLength++) {

         //creates a substring to check against isAllPalindrome method
         checkPalindrome = input.substring(indexStart, wordLength);
         //checks checkPalindrome string to see if it is a palindrome
         if (isAllPalindrome(checkPalindrome) == true){
             allPalindromes += " " + checkPalindrome;
             if (checkPalindrome.length() >= allPalindromes.length()){
                 allPalindromes = checkPalindrome;
             }
         }
         //once program reads string through once, increment index and scan text again
         if (wordLength == wordMax && indexStart < wordMax){
             indexStart++;
             wordLength = 0;
         }

     }
     System.out.println("The palindromes in the text are: ");
     System.out.println(allPalindromes);
     return allPalindromes;
 }

采纳答案by m-szalik

public static Set<CharSequence> printAllPalindromes(String input) {
    if (input.length() <= 2) {
        return Collections.emptySet();
    }
    Set<CharSequence> out = new HashSet<CharSequence>();
    int length = input.length();
    for (int i = 1; i <= length; i++) {
        for (int j = i - 1, k = i; j >= 0 && k < length; j--, k++) {
            if (input.charAt(j) == input.charAt(k)) {
                out.add(input.subSequence(j, k + 1));
            } else {
                break;
            }
        }
    }
    return out;
}

回答by left4dead

Here is the solution which displays all palindromes. (Only those palindromes which are of length greater than 3. You can change the if condition inside the loop if you want to print them all.)

这是显示所有回文的解决方案。(仅那些长度大于 3 的回文。如果要全部打印它们,可以更改循环内的 if 条件。)

Note that @jw23's solution does not display the palindromes which are of even length — only the odd length ones.

请注意,@jw23 的解决方案不显示偶数长度的回文 - 仅显示奇数长度的回文。

    public class HelloWorld{

    public static void printPalindromes(String s) {
        if (s == null || s.length() < 3)
            return;

        System.out.println("Odd Length Palindromes:");
        // Odd Length Palindromes
        for (int i=1; i<s.length()-1; i++) {
            for (int j=i-1,k=i+1; j>=0 && k<s.length(); j--,k++) {
                if (s.charAt(j) == s.charAt(k)) {
                    if (k-j+1 >= 3)
                        System.out.println(s.substring(j, k+1) + " with index " +j+ " and "+k);
                }
                else
                    break;
            }
        }

        System.out.println("\nEven Length Palindromes:");
        // Even Length Palindromes
        for (int i=1; i<s.length()-1; i++) {
            for (int j=i,k=i+1; j>=0 && k<s.length(); j--,k++) {
                if (s.charAt(j) == s.charAt(k)) {
                    if (k-j+1 >= 3)
                        System.out.println(s.substring(j, k+1) + " with index " +j+ " and "+k);
                }
                else
                    break;
            }
        }
    }

    public static void main(String[] args){
        String s = "abcbaaabbaa";
        printPalindromes(s);
    }
}

回答by TestBud

My own logic for palindrome program for all substrings

我自己的所有子串的回文程序逻辑

public class Test1 {

    public static void main(String[] args) {

        String s = "bob";

        ArrayList<Character> chr = new ArrayList<Character>();
        ArrayList<String> subs= new ArrayList<String>();

        for (int i=0;i<s.length();i++)
        {
            chr.add(s.charAt(i));
        }

        System.out.println(chr.toString());
        StringBuilder subString = new StringBuilder();
        for(int i=0; i < s.length();i++)
        {
            for(int j=i+1;j<s.length();j++)
            {
                for(int k=i;k<=j;k++)
                {
                    subString.append(chr.get(k));

                }
                System.out.println(subString.toString());
                subs.add(subString.toString());
                subString.setLength(0); 
            }
        }

        System.out.println(subs);

        for(String st : subs)
        {
            String st2 = new StringBuffer(st).reverse().toString(); 
        if(st.equals(st2))
        {
            System.out.println(st+" is a palindrome");
        }
        else
        {
            System.out.println(st+"  not a palindrome");
        }   

        }
    }

}

回答by piyush121

Simple Brute force way-->

简单的蛮力方式-->

public class AllPalindromes {

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

    public static void printAllPalindrome(String str) {
        for(int i=0;i<=str.length();i++)
            for(int j=i;j<str.length();j++)
                if(checkPalindrome(str.substring(i,j+1)))
                    System.out.println(str.substring(i,j+1));
    }

    public static void main(String[] args) {
        printAllPalindrome("abbaalla");
    }

}

回答by Raghuram

public class Palindrome
{
  static int count=0;
  public static void main(String args[])
  {
    Scanner sc=new Scanner(System.in);
    String s1=sc.next();
    String array[]=s1.split("");
    System.out.println("Palindromes are :");
    for(int i=0;i<=array.length;i++)
    {
        for(int j=0;j<i;j++)
        {
            String B=s1.substring(j,i);
            verify(B);
        }
    }
    System.out.println("\n"+count);
    sc.close();
  }
  public static void verify(String s1)
  {
    StringBuilder sb=new StringBuilder(s1);
    String s2=sb.reverse().toString();
    if(s1.equals(s2))
    {
        System.out.print(s1+" ");
        count++;
    }
  }
}

回答by Anshu Kumari

Java program to enter a string and frame a word by joining all the first character of each word.

Java 程序通过连接每个单词的所有第一个字符来输入一个字符串并构建一个单词。

Display a new word.

显示一个新词。

import java.util.*;
public class Anshu {
 public static void main(String args[]) {
  Scanner in = new Scanner(System.in)
  System.out.println("Enter a string");
  String s = in .nextLine();
  char ch = s.charAt(0);
  System.out.print(ch);
  s = s.toUpperCase;
  int l = s.length();
  for (int i = 0; i < l; i++)
   char a = s.charAt(i);
  if (Character.isWhiteSpace())
   System.out.print(s.charAt(i + 1) + "");
 }
}

回答by Soudipta Dutta

Question: All the palindromes from a word.

问题:一个单词的所有回文。

public class Test4 {
    public static void main(String[] args) {
         String a = "ProtijayiMeyeMADAMGiniiniGSoudiptaGina";
        allpalindromicsubstrings(a);

    }// main

    private static void allpalindromicsubstrings(String a) {
        Set<String> set = new HashSet<String>();
        for (int i = 0; i < a.length(); i++) {
            // odd length palindrome
            expand(a, i, i, set);
            // even length palindrome
            expand(a, i, i + 1, set);

        } // for
        set.parallelStream().filter(words -> words.length() > 1).distinct().forEach(System.out::println);
    }// ee

    private static void expand(String a, int start, int last, Set<String> set) {
        // run till a[start...last] is a palindrome
        while (start >= 0 && last <= a.length() - 1 && a.charAt(start) == a.charAt(last)) {

            set.add(a.substring(start, last + 1));
            // expand in both directions
            start--;
            last++;

        }
    }// ee

}

The output palindromes in the word => niin ADA eye MADAM iniini GiniiniG ii MeyeM ini

单词中的输出回文=> niin ADA eye MADAM iniini GiniiniG ii MeyeM ini

Print all the palindromes in a string:

打印一个字符串中的所有回文:

public class test1 {
    public static void main(String[] args) {
           String a = "Protijayi Meye MADAM GiniiniG Soudipta Gina";
           List<String> list = Arrays.stream(a.split(" ")).collect(Collectors.toList());
          System.out.println(list);
          List<String> plist = new ArrayList<>();
          for(int i = 0 ; i <list.size();i++) {
              String curr =list.get(i);
              if(ispalin(curr)) {plist.add(curr);}
          }//for
          System.out.println("palindrome list => " +plist);

}//main

    private static boolean ispalin(String curr) {
        if(curr == null || curr.length() == 0) {return false;}
        return new StringBuffer(curr).reverse().toString().equals(curr);
    }

}

The output is: palindrome list => [MADAM, GiniiniG]

输出为:回文列表 => [MADAM, GiniiniG]

Another Method in Java 8:

Java 8 中的另一种方法:

public class B {
    public static void main(String[] args) {
        String a = "Protijayi Meye MADAM GiniiniG Soudipta Gina";
        List<String> list = Arrays.stream(a.split(" ")).collect(Collectors.toList());

        // list to stream
        // for Multi Threaded environment
        Stream<String> stream = list.parallelStream();

        // also,Stream<String> stream = list.stream(); for single Threaded environment
        long palindrome = stream.filter(B::isPalindrome)// find all palindromes
                .peek(System.out::println) // write each match
                .count();// terminal - return a count
        System.out.println("Count of palindromes: " + palindrome);
        // System.out.println("List => " + list);


    }

    private static boolean isPalindrome(String aa) {

        return new StringBuffer(aa).reverse().toString().equals(aa);

    }
}

Output: GiniiniG MADAM Count of palindromes: 2

输出:GiniiniG MADAM 回文数:2

回答by Ajay Singh Meena

Print All Palindromes in the string

打印字符串中的所有回文

import java.util.*;
class AllPalindroms
{
  public static void main(String args[])
  {
    String input = "abbaalla";      
    if (input.length() <= 1) 
    {
        System.out.println("Not Palindrome Found.");
    }
    else
    {   
        int length = input.length();            
        Set<String> set = new HashSet<String>();
        for (int i = 0; i <length; i++)
        {
            //if(i==0)
            for (int j=i+1;j<length+1;j++) 
            {
                String s = input.substring(i, j);                   
                StringBuffer sb = new StringBuffer(s);
                sb.reverse();

                if(s.equals(sb.toString()) && s.length()>1)
                {                       
                    set.add(s);
                }
            }
        }           
        System.out.println(set);
    }
  }
}

回答by Manoranjan Kumar

My code to count all palindromes in a string:

我计算字符串中所有回文的代码:

import java.util.Scanner;

导入 java.util.Scanner;

public class CountPalindromeSapient { static int count = 0;

公共类 CountPalindromeSapient { static int count = 0;

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the given string: ");
    String inputStr = sc.nextLine();

    countPalindrome(inputStr);
    System.out.println("\nTotal count of Palindromes are: "+count);     
    sc.close();
}

private static int countPalindrome(String inputStr) {

    int count = 0;
    int len = inputStr.length();
    int startIndex =0;

    String subString = "";

    System.out.println( "Possible substrings are: ");
    for (int i = 0; i < len; i++) {
        for (int j = startIndex; j <= len; j++) {
            subString = inputStr.substring(startIndex, j);
            System.out.println(subString);

            count = checkPalindrome(subString);

        }
        startIndex++;
    }

    return count;
}

private static int checkPalindrome(String subString) {
    // TODO Auto-generated method stub
    int subLen = subString.length();
    boolean isPalindrome = false;
    for(int k=0; k<subLen; k++,subLen-- ) {     // Important
        if (subString.charAt(k) != subString.charAt(subLen -1)) {
            isPalindrome =  false;
            break;
        }else {
            isPalindrome = true;
        }
    }
    if(isPalindrome == true) {
        count ++;
    }
    return count;
}

}

}

回答by Shubham Gaur

     class StringTest {
    public static void main(String[] args) {
        StringTest test = new StringTest();
         boolean bool = test.checkPalindrom("abbaalla");
        if(!bool)
            System.out.println("String is not palindrom");

    }
    private boolean checkPalindrom(String k){
        int[] count= new int[k.length()];
        boolean[] arr = new boolean[k.length()];
        for(int t=0;t<k.length();t++){
            int j=0;
            char ch = k.charAt(t);
            for(int x=t+1;x<k.length();x++){
            if(j<count.length){
                if(ch == k.charAt(x))
                    count[j] = x + 1;
                else
                    count[j] = 0;
                j++;
            }

            }
            arr[t] = workOnArr(count,t,k);
        }
        for(int z=0;z<arr.length;z++){
            if(arr[z])
                return true;
        }

        return false;
    }
private boolean workOnArr(int[] s,int z,String w){
    int j = s.length - 1; 
    while(j -- > 0){
        if(s[j] != 0){
            if(isPalindrom(w.substring(z, s[j]))){
                if(w.substring(z, s[j]).length() > 1){
                    System.out.println(w.substring(z, s[j]).length());
                    System.out.println(w.substring(z, s[j]));
                }
                return true;
            }
        }
    }
    return false;
}   

private boolean isPalindrom(String s){

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

    return true;
}
    }



output:-
given palindrom are:-
abba, bb, aa, alla, ll



输出:-
给定的回文是:-
abba, bb, aa, alla, ll