|
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. |
2 | 3 | # Space: O(n * k) |
3 | 4 |
|
4 | 5 | # Given a list of unique words. Find all pairs of indices (i, j) |
|
14 | 15 | # Return [[0, 1], [1, 0], [3, 2], [2, 4]] |
15 | 16 | # The palindromes are ["dcbaabcd", "abcddcba", "slls", "llssssll"] |
16 | 17 |
|
| 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. |
17 | 51 | class TrieNode: |
18 | 52 | def __init__(self): |
19 | 53 | self.word_idx = -1 |
@@ -47,7 +81,11 @@ def is_palindrome(self, s, j): |
47 | 81 | j -= 1 |
48 | 82 | return True |
49 | 83 |
|
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. |
51 | 89 | class Solution_MLE(object): |
52 | 90 | def palindromePairs(self, words): |
53 | 91 | """ |
|
0 commit comments