脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python 实现求解字符串集的最长公共前缀方法

python 实现求解字符串集的最长公共前缀方法

2021-03-19 00:34Together_CZ Python

今天小编就为大家分享一篇python 实现求解字符串集的最长公共前缀方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

问题比较简单,给定一个字符串集合求解其中最长的公共前缀即可,这样的问题有点类似于最长公共子序列的问题,但是比求解最长最长公共子序列简单很多,因为是公共前缀,这样的话只需要挨个遍历即可,只要遍历长度结束或者结束前发现有不相同的即可终止,返回不同位置之前的子序列即可,下面是具体的实现:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!usr/bin/env python
#encoding:utf-8
 
'''
__Author__:沂水寒城
功能:求解字符串集的最长公共前缀
'''
 
def find_longest_prefix(str_list):
 '''
 求解字符串集的最长公共前缀
 '''
 str_list.sort(lambda x,y:cmp(len(x),len(y)))
 shortest_str=str_list[0]
 print str_list
 max_prefix=len(shortest_str)
 flag=0
 for i in range(max_prefix):
  for one_str in str_list:
   if one_str[i]!=shortest_str[i]:
    return shortest_str[:i]
    break
 return shortest_str
 
 
if __name__ == '__main__':
 str_list1=['abcdef','abcdekljjh','abcdelopqwe','abcdj']
 str_list2=['abcdef','abcdekljjh','abcdelopqwe','abcde']
 print 'str_list1--->', find_longest_prefix(str_list1)
 print 'str_list2--->', find_longest_prefix(str_list2)

结果如下:

 

?
1
2
3
4
5
str_list1---> ['abcdj', 'abcdef', 'abcdekljjh', 'abcdelopqwe']
abcd
str_list2---> ['abcde', 'abcdef', 'abcdekljjh', 'abcdelopqwe']
abcde
[Finished in 0.3s]

以上这篇python 实现求解字符串集的最长公共前缀方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/Together_CZ/article/details/76726723

延伸 · 阅读

精彩推荐