Find all substrings that are palindromes

后端 未结 9 665
伪装坚强ぢ
伪装坚强ぢ 2020-12-07 21:28

If the input is \'abba\' then the possible palindromes are a, b, b, a, bb, abba.
I understand that determining if string is palindrome is easy. It would be like:

9条回答
  •  攒了一身酷
    2020-12-07 21:53

    I just came up with my own logic which helps to solve this problem. Happy coding.. :-)

    System.out.println("Finding all palindromes in a given string : ");
            subPal("abcacbbbca");
    
    private static void subPal(String str) {
            String s1 = "";
            int N = str.length(), count = 0;
            Set palindromeArray = new HashSet();
            System.out.println("Given string : " + str);
            System.out.println("******** Ignoring single character as substring palindrome");
            for (int i = 2; i <= N; i++) {
                for (int j = 0; j <= N; j++) {
                    int k = i + j - 1;
                    if (k >= N)
                        continue;
                    s1 = str.substring(j, i + j);
                    if (s1.equals(new StringBuilder(s1).reverse().toString())) {
                        palindromeArray.add(s1);
                    }
                }
    
            }
            System.out.println(palindromeArray);
            for (String s : palindromeArray)
                System.out.println(s + " - is a palindrome string.");
            System.out.println("The no.of substring that are palindrome : "
                    + palindromeArray.size());
        }
    
    Output:-
    Finding all palindromes in a given string : 
    Given string : abcacbbbca
    ******** Ignoring single character as substring palindrome ********
    [cac, acbbbca, cbbbc, bb, bcacb, bbb]
    cac - is a palindrome string.
    acbbbca - is a palindrome string.
    cbbbc - is a palindrome string.
    bb - is a palindrome string.
    bcacb - is a palindrome string.
    bbb - is a palindrome string.
    The no.of substring that are palindrome : 6
    

提交回复
热议问题