|
| 1 | +''' |
| 2 | +Longest Palindromic Substring |
| 3 | +
|
| 4 | +Find the length of the longest palindromic substring. |
| 5 | +
|
| 6 | +Input: 'google' |
| 7 | +Output: 4 |
| 8 | +
|
| 9 | +========================================= |
| 10 | +Simple algorithm, for each position compare left and right side and count the length of matching. |
| 11 | + Time Complexity: O(N^2) |
| 12 | + Space Complexity: O(1) |
| 13 | +* For this problem exists a faster algorithm, called Manchester's Algorithm. Time Complexity O(N) and Space Complexity O(N). |
| 14 | +''' |
| 15 | + |
| 16 | + |
| 17 | +############ |
| 18 | +# Solution # |
| 19 | +############ |
| 20 | + |
| 21 | +def longest_palindromic_substring(s): |
| 22 | + n = len(s) |
| 23 | + longest = 1 |
| 24 | + |
| 25 | + for i in range(n): |
| 26 | + # search for palindrom with odd number of chars |
| 27 | + count_odd = compare_both_sides(s, 1, i - 1, i + 1) |
| 28 | + |
| 29 | + # search for palindrom with even number of chars |
| 30 | + count_even = compare_both_sides(s, 0, i - 1, i) |
| 31 | + |
| 32 | + # save the longest |
| 33 | + longest = max(longest, count_odd, count_even) |
| 34 | + |
| 35 | + return longest |
| 36 | + |
| 37 | +def compare_both_sides(s, count, left, right): |
| 38 | + # helper method to avoid duplicate code |
| 39 | + n = len(s) |
| 40 | + |
| 41 | + while (left >= 0) and (right < n) and (s[left] == s[right]): |
| 42 | + count += 2 |
| 43 | + left -= 1 |
| 44 | + right += 1 |
| 45 | + |
| 46 | + return count |
| 47 | + |
| 48 | + |
| 49 | +########### |
| 50 | +# Testing # |
| 51 | +########### |
| 52 | + |
| 53 | +# Test 1 |
| 54 | +# Correct result => 4 |
| 55 | +print(longest_palindromic_substring('google')) |
| 56 | + |
| 57 | +# Test 2 |
| 58 | +# Correct result => 11 |
| 59 | +print(longest_palindromic_substring('sgoaberebaogle')) |
| 60 | + |
| 61 | +# Test 3 |
| 62 | +# Correct result => 2 |
| 63 | +print(longest_palindromic_substring('abcdeef')) |
| 64 | + |
| 65 | +# Test 4 |
| 66 | +# Correct result => 7 |
| 67 | +print(longest_palindromic_substring('racecar')) |
| 68 | + |
| 69 | +# Test 5 |
| 70 | +# Correct result => 5 |
| 71 | +print(longest_palindromic_substring('abbabbc')) |
| 72 | + |
| 73 | +# Test 6 |
| 74 | +# Correct result => 10 |
| 75 | +print(longest_palindromic_substring('forgeeksskeegfor')) |