如何在Python中找到兩個字串之間最長的公共子字串?

Mary-Kate Olsen
發布: 2024-10-27 03:40:02
原創
237 人瀏覽過

How to Find the Longest Common Substring Between Two Strings in Python?

找出兩個字串中的公有子字串

辨識兩個字串共享的公用子字串是程式設計的常見任務。假設我們有兩個輸入字串,如問題陳述所示:

<br>string1 = "apples"<br>string2 = "appleses"<br>
登入後複製

在這種情況下,公有子字串是「apples」。同樣,對於更複雜的範例:

<br>string1 = "蘋果派可用"<br>string2 = "蘋果派"<br>
登入後複製

預期輸出應該是“apple pie”,它代表共享子字串。

使用 difflib 的 Pythonic 解決方案

為了在 Python 中有效地解決這個問題,我們可以利用標準庫中包含 difflib 模組。具體來說,SequenceMatcher 中的 find_longest_match() 方法可用於識別兩個字串之間最長的公共子字串。

<code class="python">from difflib import SequenceMatcher

string1 = "apple pie available"
string2 = "come have some apple pies"

match = SequenceMatcher(None, string1, string2).find_longest_match()

print(match)  # Output: Match(a=0, b=15, size=9)
print(string1[match.a:match.a + match.size])  # Output: "apple pie"
print(string2[match.b:match.b + match.size])  # Output: "apple pie"</code>
登入後複製

在3.9 之前的Python 版本中,find_longest_match() 方法需要額外的參數:

<code class="python">SequenceMatcher(None, string1, string2).find_longest_match(0, len(string1), 0, len(string2))</code>
登入後複製

透過採用這種方法,我們可以有效地從一對輸入字元串中提取公共子字串,從而簡化查找共享序列的任務。

以上是如何在Python中找到兩個字串之間最長的公共子字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!