1+ """
2+ Time: O(N x L^2), assume the average length of word is L. Note that, eversing the string takes O(L).
3+ Space: O(L), beside from ans, need `left` and `right` constantly to store the word.
4+ """
5+ class Solution (object ):
6+ def palindromePairs (self , words ):
7+ ans = set ()
8+ index = {word :i for i , word in enumerate (words )}
9+
10+ for i , word in enumerate (words ):
11+ for j in xrange (len (word )+ 1 ):
12+ left = word [:j ]
13+ right = word [j :]
14+
15+ # check if any other word that concat to the left will make palindrome: "OTHER_WORD+`left`+`right`"
16+ # The above will be palindrome only if
17+ # 1. `left` is palindrome (left==left[::-1])
18+ # 2. Exsit an "OTHER_WORD" in word in words that equals to the reverse of `right` (right[::-1] in index and index[right[::-1]]!=i).
19+ if left == left [::- 1 ]:
20+ if right [::- 1 ] in index and index [right [::- 1 ]]!= i :
21+ ans .add ((index [right [::- 1 ]], i ))
22+
23+ # check if any other word that concat to the right will make palindrome: "`left`+`right`+OTHER_WORD"
24+ # The above will be palindrome only if
25+ # 1. `rihgt` is palindrome (right==right[::-1])
26+ # 2. Exsit an "OTHER_WORD" in words that equals to the reverse of `left` (left[::-1] in index and index[left[::-1]]!=i).
27+ if right == right [::- 1 ]:
28+ if left [::- 1 ] in index and index [left [::- 1 ]]!= i :
29+ ans .add ((i , index [left [::- 1 ]]))
30+
31+ return ans
32+
33+
34+ """
35+ Time: O(N^2 x L), will cause TLE.
36+ Space: O(L), can reduce to O(1) by improving isPalindrome()
37+ """
38+ class Solution (object ):
39+ def palindromePairs (self , words ):
40+ N = len (words )
41+ ans = []
42+
43+ for i in xrange (N ):
44+ for j in xrange (N ):
45+ if i == j : continue
46+ if self .isPalindrome (words [i ]+ words [j ]):
47+ ans .append ([i , j ])
48+ return ans
49+
50+ def isPalindrome (self , word ):
51+ l = 0
52+ r = len (word )- 1
53+
54+ while l <= r :
55+ if word [l ]== word [r ]:
56+ l += 1
57+ r -= 1
58+ else :
59+ return False
60+ return True
61+
62+
0 commit comments