虾皮的一个面试题,紧急梳理一下
思路是将时间复杂度从 O ( N 2 M ) O(N^2M) O(N2M)降为 O ( N M 2 ) O(NM^2) O(NM2)
比如说对于字符串abc
,一共可以且4刀,如果:(lp=left part,rp=right part)
lp
是回文且 rp[::-1] in words
rp
是回文且 lp[::-1] in words
比如说,words = ['abc', 'cb']
,lp=a是回文且rp=‘bc’,逆在words
对于长度为L
的word,一共可以切L+1
刀
注意对于空集的判定只能有一次,否则会重复
删除空集去重情况
注:
∅
\varnothing
∅是回文(空字符串),逆序在words中,但这种情况会发生两次(遍历中),所以要去重。有两重对
∅
\varnothing
∅去重的判断方法,文末代码
lp | rp |
---|---|
∅ \varnothing ∅ | abc |
a | bc |
ab | c |
abc | ∅ \varnothing ∅ |
以下两个代码都可以A:
class Solution:
def palindromePairs(self, words: List[str]) -> List[List[int]]:
indexes={word[::-1]:i for i,word in enumerate(words)}
is_palindrome=lambda s:s==s[::-1]
N=len(words)
ret=[]
for i in range(N):
word=words[i]
L=len(word)
for j in range(L+1):
lp, rp = word[:j], word[j:] # left part, right part
if j!=0 and is_palindrome(lp) and rp in indexes and indexes[rp]!=i:
ret.append([indexes[rp], i])
if is_palindrome(rp) and lp in indexes and indexes[lp]!=i:
ret.append([i, indexes[lp]])
return ret
class Solution:
def palindromePairs(self, words: List[str]) -> List[List[int]]:
indexes={word[::-1]:i for i,word in enumerate(words)}
is_palindrome=lambda s:s==s[::-1]
N=len(words)
ret=[]
for i in range(N):
word=words[i]
L=len(word)
for j in range(L+1):
lp, rp = word[:j], word[j:] # left part, right part
if is_palindrome(lp) and rp in indexes and indexes[rp]!=i:
ret.append([indexes[rp], i])
if j!=L and is_palindrome(rp) and lp in indexes and indexes[lp]!=i:
ret.append([i, indexes[lp]])
return ret