Python Program To Find Number Of Palindrome In A String
Chapter:
Python
Last Updated:
23-09-2023 03:14:15 UTC
Program:
/* ............... START ............... */
def count_palindromic_substrings(s):
n = len(s)
count = 0
# Create a table to store whether a substring from index i to j is a palindrome.
is_palindrome = [[False] * n for _ in range(n)]
# All substrings of length 1 are palindromes.
for i in range(n):
is_palindrome[i][i] = True
count += 1
# Check for palindromes of length 2.
for i in range(n - 1):
if s[i] == s[i + 1]:
is_palindrome[i][i + 1] = True
count += 1
# Check for palindromes of length greater than 2.
for length in range(3, n + 1):
for i in range(n - length + 1):
j = i + length - 1
if s[i] == s[j] and is_palindrome[i + 1][j - 1]:
is_palindrome[i][j] = True
count += 1
return count
# Example usage:
s = "ababa"
result = count_palindromic_substrings(s)
print("Number of Palindromic Substrings:", result)
/* ............... END ............... */
Output
When you run the example with the string "ababa,"
it should print: Number of Palindromic Substrings: 7
Notes:
-
In this program, the count_palindromic_substrings function takes a string s as input and returns the count of palindromic substrings within it. It uses dynamic programming to fill a 2D table is_palindrome, where is_palindrome[i][j] is True if the substring from index i to j is a palindrome.
- The program first considers single characters as palindromes (length 1) and then checks for palindromes of length 2. After that, it iteratively checks for palindromes of increasing length by considering substrings of length 3, 4, and so on.
Tags
Python program to find number of palindrome in a string #How do you find all palindromes in a string in Python?