Re: [闲聊] 每日leetcode

楼主: dont   2024-10-06 09:35:18
1813. Sentence Similarity III
## 思路
Case1. prefix == s1, 在后面加字串 (aa, aabcd)
Case2. suffix == s1, 在前面加字串 (aa, bcdaa)
Case3. prefix+suffix == s1, 在中间加字串 (aa, abcda)
先把两个字串都转成word阵列
用two pointer检查s1跟s2的prefix跟suffix相同words个数
如果超过s1的word个数就回传True
## Code
```python
class Solution:
def areSentencesSimilar(self, sentence1: str, sentence2: str) ->
bool:
# aa aabcd True
# aa bcdaa True
# aa baacd False
# aa abcda True
words1 = sentence1.split()
words2 = sentence2.split()
if len(words1) > len(words2):
words1, words2 = words2, words1
left, right = 0, len(words1) - 1
count = len(words1)
for i in range(len(words2)):
if words2[i] != words1[left]:
break
left += 1
count -= 1
if count == 0:
return True
for i in range(len(words2)-1, -1, -1):
if words2[i] != words1[right]:
break
right -= 1
count -= 1
if count == 0:
return True
return False
```

Links booklink

Contact Us: admin [ a t ] ucptt.com