Count the number of palindromes and the longest palindrome in a give string.
Approach:
For each position of String S[i], calculate the number of odd length palindromes.
if S[i] == S[i+1] then calculate the number of even length palindromes.
while calculating odd and even length palindromes, keep track of the longest palindrome.
Time complexity: O(n^2).
Code input/output:
Input String: abacaba
Total palindromes: 5
Longes palindrome: abacaba
Palindromes are:
aba aca bacab abacaba aba
Input String: mamracecardudeabuttubathisist
Total palindromes: 11
Longes palindrome: abuttuba
Palindromes are:
mam cec aceca racecar dud tt uttu buttub abuttuba isi sis
Input String: mississippi
Total palindromes: 9
Longes palindrome: ississi
Palindromes are:
ss issi sis ssiss ississi ss issi pp ippi
Approach:
For each position of String S[i], calculate the number of odd length palindromes.
if S[i] == S[i+1] then calculate the number of even length palindromes.
while calculating odd and even length palindromes, keep track of the longest palindrome.
Time complexity: O(n^2).
Code input/output:
Input String: abacaba
Total palindromes: 5
Longes palindrome: abacaba
Palindromes are:
aba aca bacab abacaba aba
Input String: mamracecardudeabuttubathisist
Total palindromes: 11
Longes palindrome: abuttuba
Palindromes are:
mam cec aceca racecar dud tt uttu buttub abuttuba isi sis
Input String: mississippi
Total palindromes: 9
Longes palindrome: ississi
Palindromes are:
ss issi sis ssiss ississi ss issi pp ippi
No comments:
Post a Comment