📜  计算所有素长度回文子串

📅  最后修改于: 2021-05-08 17:21:41             🧑  作者: Mango

给定一个字符串str,任务是计算所有str的子串它们是回文并且其长度为素数。

例子:

方法:使用埃拉托色尼的筛,找到所有的素数,直到str的长度,因为这是海峡子字符串可以有最大长度。现在从最小素数开始,即j = 2直到j≤len(str) 。如果j为质数,则计算其长度= jstr的所有回文子串。最后打印总数。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function that returns true if sub-string
// starting at i and ending at j in str is a palindrome
bool isPalindrome(string str, int i, int j)
{
    while (i < j) {
        if (str[i] != str[j])
            return false;
        i++;
        j--;
    }
  
    return true;
}
  
// Function to count all palindromic substring
// whose lwngth is a prime number
int countPrimePalindrome(string str, int len)
{
  
    bool prime[len + 1];
    memset(prime, true, sizeof(prime));
  
    // 0 and 1 are non-primes
    prime[0] = prime[1] = false;
    for (int p = 2; p * p <= len; p++) {
  
        // If prime[p] is not changed, then it is a prime
        if (prime[p]) {
  
            // Update all multiples of p greater than or
            // equal to the square of it
            // numbers which are multiple of p and are
            // less than p^2 are already been marked.
            for (int i = p * p; i <= len; i += p)
                prime[i] = false;
        }
    }
  
    // To store the required number of sub-strings
    int count = 0;
  
    // Starting from the smallest prime till 
    // the largest length of the sub-string possible
    for (int j = 2; j <= len; j++) {
  
        // If j is prime
        if (prime[j]) {
  
            // Check all the sub-strings of length j
            for (int i = 0; i + j - 1 < len; i++) {
  
                // If current sub-string is a palindrome
                if (isPalindrome(str, i, i + j - 1))
                    count++;
            }
        }
    }
  
    return count;
}
  
// Driver Code
int main()
{
    string s = "geeksforgeeks";
    int len = s.length();
  
    cout << countPrimePalindrome(s, len);
  
    return 0;
}


Java
// Java implementation of the approach 
import java.util.Arrays;
  
class GfG
{
  
    // Function that returns true if 
    // sub-string starting at i and 
    // ending at j in str is a palindrome 
    static boolean isPalindrome(String str, int i, int j) 
    { 
        while (i < j) 
        { 
            if (str.charAt(i) != str.charAt(j)) 
                return false; 
            i++; 
            j--; 
        } 
      
        return true; 
    } 
      
    // Function to count all palindromic substring 
    // whose lwngth is a prime number 
    static int countPrimePalindrome(String str, int len) 
    { 
      
        boolean[] prime = new boolean[len + 1]; 
        Arrays.fill(prime, true); 
      
        // 0 and 1 are non-primes 
        prime[0] = prime[1] = false; 
        for (int p = 2; p * p <= len; p++) 
        { 
      
            // If prime[p] is not changed,
            // then it is a prime 
            if (prime[p])
            { 
      
                // Update all multiples of p greater than or 
                // equal to the square of it 
                // numbers which are multiple of p and are 
                // less than p^2 are already been marked. 
                for (int i = p * p; i <= len; i += p) 
                    prime[i] = false; 
            } 
        } 
      
        // To store the required number of sub-strings 
        int count = 0; 
      
        // Starting from the smallest prime till 
        // the largest length of the sub-string possible 
        for (int j = 2; j <= len; j++) 
        { 
      
            // If j is prime 
            if (prime[j]) 
            { 
      
                // Check all the sub-strings of length j 
                for (int i = 0; i + j - 1 < len; i++) 
                { 
      
                    // If current sub-string is a palindrome 
                    if (isPalindrome(str, i, i + j - 1)) 
                        count++; 
                } 
            } 
        } 
        return count; 
    } 
      
    // Driver code
    public static void main(String []args)
    {
        String s = "geeksforgeeks"; 
        int len = s.length(); 
  
        System.out.println(countPrimePalindrome(s, len));
    }
}
  
// This code is contributed by Rituraj Jain


Python3
# Python3 implementation of the approach
import math as mt
  
# Function that returns True if sub-str1ing
# starting at i and ending at j in str1 
# is a palindrome
def isPalindrome(str1, i, j):
  
    while (i < j):
        if (str1[i] != str1[j]):
            return False
        i += 1
        j -= 1
      
    return True
      
# Function to count all palindromic substr1ing
# whose lwngth is a prime number
def countPrimePalindrome(str1, Len):
  
    prime = [True for i in range(Len + 1)]
  
    # 0 and 1 are non-primes
    prime[0], prime[1] = False, False
    for p in range(2, mt.ceil(mt.sqrt(Len + 1))):
  
        # If prime[p] is not changed, 
        # then it is a prime
        if (prime[p]):
  
            # Update all multiples of p greater 
            # than or equal to the square of it
            # numbers which are multiple of p 
            # and are less than p^2 are already 
            # been marked.
            for i in range(2 * p, Len + 1, p):
                prime[i] = False
          
    # To store the required number 
    # of sub-str1ings
    count = 0
  
    # Starting from the smallest prime 
    # till the largest Length of the 
    # sub-str1ing possible
    for j in range(2, Len + 1):
  
        # If j is prime
        if (prime[j]):
  
            # Check all the sub-str1ings of 
            # Length j
            for i in range(Len + 1 - j):
  
                # If current sub-str1ing is a palindrome
                if (isPalindrome(str1, i, i + j - 1)):
                    count += 1
              
    return count
  
# Driver Code
s = "geeksforgeeks"
Len = len(s)
  
print( countPrimePalindrome(s, Len))
  
# This code is contributed by 
# Mohit kumar 29


C#
// C# implementation of the approach 
using System;
  
class GfG
{
  
// Function that returns true if 
// sub-string starting at i and 
// ending at j in str is a palindrome 
static bool isPalindrome(string str, 
                         int i, int j) 
{ 
    while (i < j) 
    { 
        if (str[i] != str[j]) 
            return false; 
        i++; 
        j--; 
    } 
  
    return true; 
} 
  
// Function to count all palindromic 
// substring whose lwngth is a prime number 
static int countPrimePalindrome(string str, 
                                int len) 
{ 
  
    bool[] prime = new bool[len + 1]; 
    Array.Fill(prime, true); 
  
    // 0 and 1 are non-primes 
    prime[0] = prime[1] = false; 
    for (int p = 2; p * p <= len; p++) 
    { 
  
        // If prime[p] is not changed,
        // then it is a prime 
        if (prime[p])
        { 
  
            // Update all multiples of p greater 
            // than or equal to the square of it 
            // numbers which are multiple of p 
            // and are less than p^2 are already
            // been marked. 
            for (int i = p * p; i <= len; i += p) 
                prime[i] = false; 
        } 
    } 
  
    // To store the required number
    // of sub-strings 
    int count = 0; 
  
    // Starting from the smallest prime 
    // till the largest length of the 
    // sub-string possible 
    for (int j = 2; j <= len; j++) 
    { 
  
        // If j is prime 
        if (prime[j]) 
        { 
  
            // Check all the sub-strings of 
            // length j 
            for (int i = 0; 
                     i + j - 1 < len; i++) 
            { 
  
                // If current sub-string is a 
                // palindrome 
                if (isPalindrome(str, i, i + j - 1)) 
                    count++; 
            } 
        } 
    } 
    return count; 
} 
  
// Driver code
public static void Main()
{
    string s = "geeksforgeeks"; 
    int len = s.Length; 
  
    Console.WriteLine(countPrimePalindrome(s, len));
}
}
  
// This code is contributed by Code_Mech


PHP


输出:
2
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”