80 likes | 197 Vues
Tony is celebrating his birthday by arranging letters around a cake and wants the largest slice containing a palindrome. This guide explores various algorithms for detecting palindromic substrings efficiently. It covers brute force methods with O(n^3) complexity, dynamic programming with O(n^2) complexity but significant memory use, and advanced techniques like Manacher's algorithm that operates in linear time O(n). The goal is to find the maximum palindrome length amidst the given constraints, showcasing sample input and output for the problem.
E N D
Happy Birthday Tony Palindromes
Brute force • Can search all possible pairs (i, j): 1<=i <= j <=n and check if the substring is a palindrome. • Runs in O(n^3) time. • Can use this to find all possible palindromes, number of palindromes, longest palindrome, etc.
Dynamic Programming • Store bool isPal [1...n][1...n]; • isPal[i][i] is always true. • isPal[i][i+1] is true iff str[i] == str[i+1] • In general, isPal[i][j] is true if isPal[i+1][j-1] is true and str[i]==str[j] • O(n^2) time and O(n^2) memory • Uses an unnecessary amount of memory • Can find longest palindrome, count palindromes, etc., and can determine if a substring is a palindrome in O(1) time, but no real reason to use it
Searching From Center • For each possible center (there are 2n-1 of them because the center doesn't have to be a letter), search until the two sides don't match. • Runs in O(n^2) time: O(n) per center. • Finds maximal palindrome from every center. • Can this to find number of palindromes or longest palindrome, and can determine if a substring is a palindrome in O(1) time.
Manacher's algorithm • An advanced linear time (O(n)) algorithm to find maximal palindrome at every center. • Usually you insert a dummy character between each letter, so that each letter is now a valid center (remember there are 2n-1 centers). • Takes advantage of symmetry. • Usually you won't need it.
Potw • Tony is making a round birthday cake to celebrate his birthday. • Tony has arranged N letters around the perimeter of his cake. • He wishes to give a slice of cake (1 to N consecutive letters) to someone special, so he wants it to be as large as possible. • Since Tony likes palindromes, he wants the letters on the slice to form a palindrome. • What's the largest slice Tony can cut?
Potw • Input format:Line 1: a string of N letters • Output format:Line 1: L, the length of the longest palindrome • Sample input:abaacaba • Sample output: (abaaba is the palindrome)6 • Constraints:1<=N<=100: 10 points1<=N<=1000: 20 points