Re: [閒聊] 每日leetcode

看板Marginalman作者 (dont)時間1年前 (2024/10/06 09:35), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串950/1554 (看更多)
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
文章代碼(AID): #1d0UbOQ4 (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1d0UbOQ4 (Marginalman)