- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to count number of palindromic substrings in Python
Suppose we have a string s, we have to find the number of palindromic substrings in s.
So, if the input is like s = "level", then the output will be 7, as the palindromic substrings are: ["l","e","v","e","l","eve","level"]
To solve this, we will follow these steps −
- Define a function check_palindrome(). This will take string, left, right
- ans := 0
- while left >= 0 and right < size of s, do
- if s[left] is same as s[right], then
- ans := ans + 1
- left := left - 1
- right := right + 1
- otherwise,
- return ans
- if s[left] is same as s[right], then
- return ans
- From the main method, do the following −
- ans := 0
- for char_index in range 0 to size of s, do
- ans := ans + check_palindrome(s, char_index - 1, char_index + 1)
- ans := ans + check_palindrome(s, char_index, char_index + 1)
- return (ans) + size of s
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, s): def check_palindrome(string, left, right): ans = 0 while left >= 0 and right < len(s): if s[left] == s[right]: ans += 1 left -= 1 right += 1 else: return ans return ans ans = 0 for char_index in range(len(s)): ans += check_palindrome(s, char_index - 1, char_index + 1) ans += check_palindrome(s, char_index, char_index + 1) return (ans) + len(s) ob = Solution() print(ob.solve("level"))
Input
"level"
Output
7
Advertisements