Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def palindromeSubStrings(S):
- uniquePalindromeSubstrings = dict()
- n = len(S)
- # Table for storing results, 2 rows for odd-
- # and even-length palindromes
- resultsTable = [[0 for x in range(n+1)] for y in range(2)]
- # Find all sub-string palindromes from the given input
- # Insert square brackets before and after the string
- # to iterate easily over the string S
- S = "[" + S + "]"
- for j in range(2):
- palindromeRadius = 0 # length of 'palindrome radius'
- resultsTable[j][0] = 0
- i = 1
- while i <= n:
- # Expand palindrome centered at i
- while S[i - palindromeRadius - 1] == S[i + j + palindromeRadius]:
- palindromeRadius += 1 # Incrementing the length of palindromic
- # radius as and when we find valid palindrome
- # Assign the found palindromic length to odd/even
- # length array
- resultsTable[j][i] = palindromeRadius
- k = 1
- while (resultsTable[j][i - k] != palindromeRadius - k) and (k < palindromeRadius):
- resultsTable[j][i+k] = min(resultsTable[j][i-k], palindromeRadius - k)
- k += 1
- palindromeRadius = max(palindromeRadius - k, 0)
- i += k
- # remove the square brackets for the string put previously
- S = S[1:len(S)-1]
- # Insert all obtained palindromes in a hash map/dictionary to
- # find only unique palindrome
- uniquePalindromeSubstrings[S[0]] = 1
- for i in range(1,n):
- for j in range(2):
- for palindromeRadius in range(resultsTable[j][i],0,-1):
- uniquePalindromeSubstrings[S[i - palindromeRadius - 1 : i - palindromeRadius - 1 + 2 * palindromeRadius + j]] = 1
- uniquePalindromeSubstrings[S[i]] = 1
- # printing all unique palindromic substrings from the hash map
- palindromeSubstringsCount = 0
- for i in uniquePalindromeSubstrings:
- palindromeSubstringsCount += 1
- print(i)
- print("Palindrome Substrings Count =",palindromeSubstringsCount)
- palindromeSubStrings("bananananananananananananananananananana")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement