Skip to content

Commit 1100133

Browse files
committed
Update palindrome-pairs.py
1 parent f0b22d0 commit 1100133

File tree

1 file changed

+40
-2
lines changed

1 file changed

+40
-2
lines changed

Python/palindrome-pairs.py

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
# Time: O(n * k), n is the number of the words, k is the max length of the words.
1+
# Time: O(n * k^2), n is the number of the words,
2+
# k is the max length of the words.
23
# Space: O(n * k)
34

45
# Given a list of unique words. Find all pairs of indices (i, j)
@@ -14,6 +15,39 @@
1415
# Return [[0, 1], [1, 0], [3, 2], [2, 4]]
1516
# The palindromes are ["dcbaabcd", "abcddcba", "slls", "llssssll"]
1617

18+
19+
class Solution(object):
20+
def palindromePairs(self, words):
21+
"""
22+
:type words: List[str]
23+
:rtype: List[List[int]]
24+
"""
25+
def is_palindrome(s, start, end):
26+
while start <= end:
27+
if s[start] != s[end]:
28+
return False
29+
start += 1
30+
end -= 1
31+
return True
32+
33+
res = []
34+
lookup = {}
35+
for i, word in enumerate(words):
36+
lookup[word] = i
37+
38+
for i in xrange(len(words)):
39+
for j in xrange(len(words[i]) + 1):
40+
if is_palindrome(words[i], j, len(words[i]) - 1):
41+
suffix = words[i][:j][::-1]
42+
if suffix in lookup and lookup[suffix] != i:
43+
res.append([i, lookup[suffix]])
44+
if j > 0 and is_palindrome(words[i], 0, j - 1):
45+
prefix = words[i][j:][::-1]
46+
if prefix in lookup and lookup[prefix] != i:
47+
res.append([lookup[prefix], i])
48+
return res
49+
50+
# Trie solution.
1751
class TrieNode:
1852
def __init__(self):
1953
self.word_idx = -1
@@ -47,7 +81,11 @@ def is_palindrome(self, s, j):
4781
j -= 1
4882
return True
4983

50-
84+
# Time: O(n * k^2 + r), n is the number of the words, k is the max length of the words.
85+
# k is the max length of the words,
86+
# r is the number of the result.
87+
# Space: O(n * k)
88+
# Trie solution.
5189
class Solution_MLE(object):
5290
def palindromePairs(self, words):
5391
"""

0 commit comments

Comments
 (0)