Find the longest palindrome in a string
Anonymous
The way I'd go about this is iterate through each letter of the string to produce a starting letter in a potential palindrome, then iterate through each letter from the starting letter to the end of the string to test if the string is a palindrome. To test for a palindrome, compare the first and last letters to each other, and if they match, test the next closest two letters. Alternatively, you can make your code run faster by using the second character as a 'pivot' for the palindrome, i.e. the middle character for which the string must be symmetrical on either end. Note that the determination of whether a string is a palindrome or not depends on whether the string is odd or even in length. Runtime: O(N^2) e.g. Consider the string "abdqdbd". I will use square brackets to indicate when a palindrome is found, and a capital letter to indicate the location of the pivot. 1. Start with the first letter 'a', and iterate through each letter from this letter to the middle of the string using a pivot. start=0, pivot=0: ['A'], 'Ab' => length = 1 - NEW MAX start=0, pivot=1: 'aBd', 'aBdq' start=0, pivot=2: 'abDqd', 'abDqdb' start=0, pivot=3: 'abdQdbd', 2. Start at the next letter and continue. start=1, pivot=1: ['B'], 'Bd' => length = 1 start=1, pivot=2: 'bDq', 'bDqd' start=1, pivot=3: ['bdQdb'], 'bdQdbd' => length = 5 - NEW MAX 3. Start at the next letter and continue. start=2, pivot=2: ['D'], 'Dq' => length = 1 start=2, pivot=3: 'dQd', 'dQdb' start=2, pivot=4: 'dqDbd', 4. Start at the next letter and continue. start=3, pivot=3: ['Q'], 'Qd' => length = 1 start=3, pivot=4: 'qDb', 'qDbd' 5. Start at the next letter and continue. start=4, pivot=4: ['D'], 'Db' => length = 1 start=4, pivot=5: ['dBd'], => length = 3 6. Start at the next letter and continue. start=5, pivot=5: ['B'], 'Bd' => length = 1 7. Start at the next letter and continue. start=6, pivot=6: ['D'], => length = 1 8. Done - return 5
Check out your Company Bowl for anonymous work chats.