找到字符串中的所有回文

时间:2014-02-27 16:59:28

标签: java loops palindrome

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

示例:“abbaalla”

它循环创建一个随循环进展而变化的子字符串。

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

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

示例:检查回文“b”“bb”“bba”等等。

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

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

输出:“abba alla”

此程序当前导致:字符串索引超出范围:-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;
 }

10 个答案:

答案 0 :(得分:11)

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;
}

答案 1 :(得分:4)

简单的暴力方式 - &gt;

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");
    }

}

答案 2 :(得分:3)

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

请注意,@ 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);
    }
}

答案 3 :(得分:1)

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++;
    }
  }
}

答案 4 :(得分:0)

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

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");
        }   

        }
    }

}

答案 5 :(得分:0)

问题:一句话中的所有回文。

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

}

单词中的输出回文=&gt; niin ADA 眼睛 夫人 iniini GiniiniG 二 MeyeM INI

以字符串形式打印所有回文:

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);
    }

}

输出为:回文列表=&gt; [MADAM,GiniiniG]

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);

    }
}

输出: GiniiniG 夫人 回文数:2

答案 6 :(得分:0)

打印字符串中的所有回文

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);
    }
  }
}

答案 7 :(得分:0)

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

导入java.util.Scanner;

公共类CountPalindromeSapient {     静态整数计数= 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;
}

}

答案 8 :(得分:0)

     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;
}
    }



输出:-
给定palindrom是:
abba,bb,aa,alla,ll

答案 9 :(得分:-2)

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

显示新单词。

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) + "");
 }
}