代码仓库:Github | Leetcode solutions @doubleZ0108 from Peking University.
(1)
"a A b A"
"A"
(2)
"ByI BMyQIqce b bARkkMaABi vlR RLHhqjNzCN oXvyK zRXR q ff B yHS OD KkvJA P JdWksnH"
"B"
(3)
"A aA"
"A A"
(4)
"A B C D B B"
"A B B"
class Solution:
# 解法2
def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool:
if len(sentence1) < len(sentence2): sentence1, sentence2 = sentence2, sentence1
words1, words2 = sentence1.split(" "), sentence2.split(" ")
i, j = 0, -1
while i<len(words1) and i<len(words2) and words1[i]==words2[i]:
i += 1
while j>-len(words1)-1 and j>-len(words2)-1 and len(words2)+j+1>i and words1[j]==words2[j]:
j -= 1
return i-j-1 == len(words2)
# 解法1
def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool:
if len(sentence1) == len(sentence2): return sentence1==sentence2
if len(sentence1) < len(sentence2): sentence1, sentence2 = sentence2, sentence1
def similar(sentence1, sentence2):
words1, words2 = sentence1.split(" "), sentence2.split(" ")
freq1, freq2 = Counter(words1), Counter(words2)
for key, val in freq2.items():
if key not in freq1: return False
if val>freq1[key]: return False
if words1[:len(words2)] == words2 or words1[-len(words2):]==words2: return True
i, j = 0, 0
cnt = 0
while i<len(words1) and j<len(words2):
if words1[i] == words2[j]:
i += 1
j += 1
continue
else:
cnt += 1
if cnt==1:
i += 1
while i<len(words1) and words1[i]!=words2[j]:
i += 1
if cnt>1:
return False
if cnt==1:
return i==len(words1)
elif cnt==0:
return True
return similar(sentence1, sentence2) or similar(sentence1[::-1], sentence2[::-1])