面試題目:
1. 用PY實現求任意兩個字符串最長的公共子串?
解題思路:
1. 先求出長度最小的字符串,然後遍歷其索引,這樣可以避免字符串索引溢出,然後判斷對應索引的值是否相同,相同的話就加到目標字典,不同的話就更新目標字典索引,但不存儲,最後再按照值長度逆向排序取出第一個元素即可.
具體實現:
#!/usr/bin/env python # -*- coding: utf-8 -*- """ # # Authors: limanman # OsChina: http://xmdevops.blog.51cto.com/ # Purpose: # """ # 說明: 導入公共模塊 # 說明: 導入其它模塊 def get_most_part(sstr, tstr): s_len = len(sstr) t_len = len(tstr) r = {} count = 0 # 說明: 遍歷長度較小者長度防止溢出 for i in xrange(s_len if s_len <= t_len else t_len): # 說明: 如果兩個字符相同則追加 if sstr[i] == tstr[i]: r.setdefault(count, []).append(sstr[i]) else: # 說明: 否則改變字典索引 count = i # 說明: 對結果集排序 value = sorted(r.itervalues(), key=lambda _: len(_), reverse=True) if not value: return '' return ''.join(value[0]) if __name__ == '__main__': print get_most_part('ayx', 'yxz')