Skip to content

longest_palindrome #11556

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions strings/longest_palindrome
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import timeit

def longest_palindrome(s: str) -> str:
if s == s[::-1] or len(s) == 1:
return s
else:
res = [s[i:j] for i in range(len(s)) for j in range(i + 1, len(s) + 1)]
output = ""
for k in res:
if k == k[::-1]:
if len(k) > len(output) or (len(k) == len(output) and res.index(k) < res.index(output)):
output = k
return output


# Test cases with longer strings containing multiple palindromes
test_data = {
"abacdfgdcaba": "aba",
"abcdcbacdcba": "abcdcba",
"aabbcbbaaaab": "aabbcbbaa",
"racecarlevelcivic": "racecar",
"madamimadam": "madamimadam",
"abccbaabcdcb": "abccba",
"noonracecar": "racecar",
"aabbcccbbbaa": "bbcccbb",
"detartrated": "detartrated",
"civicradarlevel": "civic",

# Additional complex cases
"babad": "bab",
"cbbd": "bb",
"forgeeksskeegfor": "geeksskeeg",
"abacabadabacaba": "abacabadabacaba",
"a": "a",
"bb": "bb",
"pqrzzzzzyxwvutsrqponmlkjihgfedcba": "zzzzz",
"abcdefg": "a",
"noonracecarlevel": "racecar",
"abcdedcbaefg": "abcdedcba",
"abacabad": "abacaba",
"aaaaaaa": "aaaaaaa",

# Additional large test cases
"a" * 1000: "a" * 1000,
}


def benchmark():
for key, value in test_data.items():
start_time = timeit.default_timer()
result = longest_palindrome(key)
end_time = timeit.default_timer()
elapsed_time = end_time - start_time

print(f"{key[:30]:<35} -> Longest Palindrome: {result} (Time: {elapsed_time:.6f} seconds)")
assert result == value, f"Test failed for {key}. Expected {value}, but got {result}"

# If all tests pass
print("All tests passed!")


# Main code block
if __name__ == "__main__":
benchmark()