精華區beta Marginalman 關於我們 聯絡資訊
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 ``` -- https://i.imgur.com/kyBhy6o.jpeg -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 185.213.82.123 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1728178520.A.684.html