kealtuve
kealtuve

Reputation: 59

find all palindromes in string

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..

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..

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"

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

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

Upvotes: 2

Views: 50237

Answers (10)

Soudipta Dutta
Soudipta Dutta

Reputation: 2122

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

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]

Another Method in 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

Upvotes: 0

Shubham Gaur
Shubham Gaur

Reputation: 1

     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

Upvotes: 0

Manoranjan Kumar
Manoranjan Kumar

Reputation: 1

My code to count all palindromes in a string:

import java.util.Scanner;

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

}

Upvotes: 0

Ajay Singh Meena
Ajay Singh Meena

Reputation: 55

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

Upvotes: 0

left4dead
left4dead

Reputation: 51

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

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

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

Upvotes: 3

TestBud
TestBud

Reputation: 69

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

        }
    }

}

Upvotes: 0

Anshu Kumari
Anshu Kumari

Reputation: 1

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

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

Upvotes: -2

m-szalik
m-szalik

Reputation: 3654

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

Upvotes: 12

Raghuram
Raghuram

Reputation: 11

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

Upvotes: 1

piyush121
piyush121

Reputation: 515

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

}

Upvotes: 6

Related Questions