📌  相关文章
📜  计算字符串中的所有回文子字符串 |设置 2

📅  最后修改于: 2022-05-13 01:57:08.935000             🧑  作者: Mango

计算字符串中的所有回文子字符串 |设置 2

给定一个字符串,任务是计算给定字符串中的所有回文子串。回文子串的长度大于或等于 2。

Examples:
Input : str = "abaab"
Output: 3
Explanation : 
All palindrome substring are :
 "aba", "aa", "baab" 

Input : str = "abbaeae"
Output: 4
Explanation : 
All palindrome substring are : 
"bb", "abba", "aea", "eae":

我们在下面的帖子中讨论了基于动态规划的解决方案。

计算字符串中的所有回文子字符串 |设置 1

这里讨论的解决方案是最长回文子串问题的扩展。这个想法是对于给定输入字符串中的每个字符,我们将其视为回文的中点并在两个方向上扩展它以找到所有偶数和奇数长度的回文。我们使用 hashmap 来跟踪所有长度大于 1 的不同回文,并返回包含所有可能回文子串计数的映射大小。

下面给出了 C++ 实现。

CPP
// C++ program to count all distinct palindromic
// substrings of a string.
#include 
using namespace std;
  
// Returns total number of palindrome substring of
// length greater than equal to 2
int countPalindromes(string s)
{
    unordered_map m;
    for (int i = 0; i < s.length(); i++) {
  
        // check for odd length palindromes
        for (int j = 0; j <= i; j++) {
  
            if (!s[i + j])
                break;
  
            if (s[i - j] == s[i + j]) {
  
                // check for palindromes of length
                // greater than 1
                if ((i + j + 1) - (i - j) > 1)
                    m[s.substr(i - j, 
                        (i + j + 1) - (i - j))]++;
  
            } else
                break;
        }
  
        // check for even length palindromes
        for (int j = 0; j <= i; j++) {
            if (!s[i + j + 1])
                break;
            if (s[i - j] == s[i + j + 1]) {
  
                // check for palindromes of length 
                // greater than 1
                if ((i + j + 2) - (i - j) > 1)
                    m[s.substr(i - j, 
                         (i + j + 2) - (i - j))]++;
  
            } else
                break;
        }
    }
    return m.size();
}
  
// Driver code
int main()
{
    string s = "abbaeae";
    cout << countPalindromes(s) << endl;
    return 0;
}
Output:4
Time complexity O(n2)Auxiliary Space O(n)We can easily extend this solution to print all palindromic substrings also. We need to simply traverse the map m and print its content.Another Approach is to use Java String Class, to do so,Iterate the loop twice for substring, get the substring of a string using substring() method.Reverse the substring using StringBuffer Class method reverse()Check for palindrome with substring and reverse substringIf it is palindrome increment the count and return the count at last


Java
// Java Program to count palindrome substring
// in a string
public class PalindromeSubstring {
      
    // Method which return count palindrome substring
    static int countPS(String str){
        String temp = "";
        StringBuffer stf;
        int count = 0;
        // Iterate the loop twice
        for (int i = 0; i < str.length(); i++) {
            for (int j = i + 1; j <= str.length(); j++) {
                // Get each substring
                temp = str.substring(i, j);
                  
                // If length is greater than or equal to two
                // Check for palindrome    
                if (temp.length() >= 2) {
                    // Use StringBuffer class to reverse the string
                    stf = new StringBuffer(temp);
                    stf.reverse();
                    // Compare substring with reverse of substring
                    if (stf.toString().compareTo(temp) == 0)
                        count++;
                }
            }
        }
        // return the count
        return count;
    }
      
    // Driver Code
    public static void main(String args[]) throws Exception {
        // Declare and initialize the string
        String str = "abbaeae";
        // Call the method
        System.out.println(countPS(str));
    }
} // This code is contributes by hungundji


C#
// C# Program to count palindrome substring
// in a string 
using System;
  
class GFG
{
      
    // Method which return count palindrome substring
    static int countPS(String str)
    {
        String temp = "";
        String stf;
        int count = 0;
          
        // Iterate the loop twice
        for (int i = 0; i < str.Length; i++) 
        {
            for (int j = i + 1; 
                     j <= str.Length; j++)
            {
                // Get each substring
                temp = str.Substring(i, j-i);
                  
                // If length is greater than or equal to two
                // Check for palindrome 
                if (temp.Length >= 2)
                {
                    // Use StringBuffer class to reverse 
                    // the string
                    stf = temp;
                    stf = reverse(temp);
                      
                    // Compare substring with reverse of substring
                    if (stf.ToString().CompareTo(temp) == 0)
                        count++;
                }
            }
        }
          
        // return the count
        return count;
    }
      
    static String reverse(String input) 
    {
        char[] a = input.ToCharArray();
        int l, r = 0;
        r = a.Length - 1;
  
        for (l = 0; l < r; l++, r--)
        {
            // Swap values of l and r 
            char temp = a[l];
            a[l] = a[r];
            a[r] = temp;
        }
        return String.Join("",a);
    }
      
    // Driver Code
    public static void Main(String []args)
    {
        // Declare and initialize the string
        String str = "abbaeae";
          
        // Call the method
        Console.WriteLine(countPS(str));
    }
} 
  
// This code is contributed by Rajput-Ji


输出:
4

时间复杂度 O(n 2 )
辅助空间 O(n)