GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — coding-problems/Strings/longest_palindromic_substring.py at master · mickey-lab/coding-problems

Expand file tree

/

longest_palindromic_substring.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
75 lines (54 loc) · 1.65 KB
/

longest_palindromic_substring.py

Copy path

File metadata and controls

75 lines (54 loc) · 1.65 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
'''
Longest Palindromic Substring
Find the length of the longest palindromic substring.
Input: 'google'
Output: 4
=========================================
Simple algorithm, for each position compare left and right side and count the length of matching.
Time Complexity: O(N^2)
Space Complexity: O(1)
* For this problem exists a faster algorithm, called Manchester's Algorithm. Time Complexity O(N) and Space Complexity O(N).
'''
############
# Solution #
############
def longest_palindromic_substring(s):
n = len(s)
longest = 1
for i in range(n):
# search for palindrom with odd number of chars
count_odd = compare_both_sides(s, 1, i - 1, i + 1)
# search for palindrom with even number of chars
count_even = compare_both_sides(s, 0, i - 1, i)
# save the longest
longest = max(longest, count_odd, count_even)
return longest
def compare_both_sides(s, count, left, right):
# helper method to avoid duplicate code
n = len(s)
while (left >= 0) and (right < n) and (s[left] == s[right]):
count += 2
left -= 1
right += 1
return count
###########
# Testing #
###########
# Test 1
# Correct result => 4
print(longest_palindromic_substring('google'))
# Test 2
# Correct result => 11
print(longest_palindromic_substring('sgoaberebaogle'))
# Test 3
# Correct result => 2
print(longest_palindromic_substring('abcdeef'))
# Test 4
# Correct result => 7
print(longest_palindromic_substring('racecar'))
# Test 5
# Correct result => 5
print(longest_palindromic_substring('abbabbc'))
# Test 6
# Correct result => 10
print(longest_palindromic_substring('forgeeksskeegfor'))
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.