LeetCode每日一题:Day16

发布于 2023-01-16  91 次阅读


句子相似性 III

难度

  • Easy
  • Medium
  • Hard

思路

要使得插入一个句子就能变为相同句子,则短句要么是长句的前缀,要么是长句的后缀,要么可以将短句拆分成两部分,分别作为长句的前后缀。

将两个句子拆分成两个单词列表,对比上面几种情况即可。

代码

class Solution:
    def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool:
        s1, s2 = [], []
        tmp = ""
        for ch in sentence1:
            if ch != ' ': tmp += ch
            else:
                s1.append(tmp)
                tmp = ""
        s1.append(tmp)
        tmp = ""
        for ch in sentence2:
            if ch != ' ': tmp += ch
            else:
                s2.append(tmp)
                tmp = ""
        s2.append(tmp)

        if len(s1) < len(s2):
            tmp = list(s1)
            s1 = list(s2)
            s2 = list(tmp)
        i = j = 0
        while i < len(s1) and j < len(s2) and s1[i] == s2[j]:
            i += 1
            j += 1
        if j == len(s2): return True
        i = len(s1) - (len(s2) - j)
        while i < len(s1) and j < len(s2) and s1[i] == s2[j]:
            i += 1
            j += 1
        if i == len(s1) and j == len(s2):
            return True
        else:
            return False