python - python中字符串的最大公约数

标签 python string algorithm longest-substring

我想要一个给定列表的python函数

mystrings = ['abcde', 'abcdf', 'abcef', 'abcnn']

返回字符串 'abc',即列表中所有元素包含的最长片段。我有一个解决方案,它只是循环遍历 mystring[0] 的切片,并将其与其余部分进行比较,并在找到第一个不匹配的子字符串时跳出循环。但是,我怀疑一定有一种更高效、更优雅、更像 Python 的方式来做到这一点。

有人可以指出如何正确执行此操作吗?

最佳答案

按照你描述的方式,你想要起点处的最大子串:

>>> os.path.commonprefix(['abcde', 'abcdf', 'abcef', 'abcnn'])
'abc'

关于python - python中字符串的最大公约数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7879194/

相关文章:

c++ - 找不到 vector 使用中的 fatal error

algorithm - 递归下降相同前缀

algorithm - 凸包 : known number of points but not points itself

mysql - 可以删除 MySQL 字段中 'space' 之后的所有内容吗?

python - Scikit Learn - K-Means - 弯头 - 标准

python/gspread - 如何使用数据列表更新一系列单元格?

python - 根据 lambda 排序字典 : handling exceptions

c++ - c++ - 如何限制char数组仅从c++中的字符串中获取a和b?

c# - 将GPS数据转换为纬度和经度c#

python - 为什么这可以解决 matplotlib 的 'no $DISPLAY environment' 问题?