zoukankan      html  css  js  c++  java
  • 【intern】最长公共子串、编辑距离、KMP 等

    这可能是一个很长的blog……

    # from https://blog.csdn.net/justheretobe/article/details/51764587
    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    
    def lcs(s1,s2):
        m = len(s1)
        n = len(s2)
        counter = [[0]*(n+1) for x in range(m+1)]
        longest = 0
        lcs_set = set()
        for i in range(1,m+1):
            for j in range(1,n+1):
                if s1[i-1] == s2[j-1]:
                    c = counter[i-1][j-1] + 1
                    counter[i][j] = c
                    if c > longest:
                        lcs_set = set()
                        longest = c
                        lcs_set.add(s1[i-c:i])
                    elif c == longest:
                        lcs_set.add(s1[i-c:i])
        return lcs_set
    
    
    if __name__ == "__main__":
        assert lcs('academy', 'abracadabra') == {'acad'}
        assert lcs('ababc', 'abcdaba') == {'aba','abc'}
        assert lcs('abcdefgh', 'cdefgh') == {'cdefgh'}
        assert lcs('abcdefgh', '') == set()
        print('assert complete!')

    如果不需要存所有的最长公共子串结果,可以把lcs_set变为字符串。

    获取string中的最长回文字符串还可以使用寻找两个字符串最长公共substring的方法解答: 
    1. s1=‘给定字符串’ 
    2. s2=‘给定字符串的反序’ 
    3. 比较s1与s2, 获取两个字符串中最长的公共字符串,即为s1最长的回文字符串 

    (⬆️这个想法可以借鉴)

    ==================================================================================================================

    编辑距离:

    def normal_leven(str1, str2):
        len_str1 = len(str1) + 1
        len_str2 = len(str2) + 1
        # 创建矩阵
        matrix = [0 for n in range(len_str1 * len_str2)]
        # 矩阵的第一行
        for i in range(len_str1):
            matrix[i] = i
        print(matrix)
        # 矩阵的第一列
        for j in range(0, len(matrix), len_str1):
            if j % len_str1 == 0:
                matrix[j] = j // len_str1
        # 根据状态转移方程逐步得到编辑距离
        for i in range(1, len_str1):
            for j in range(1, len_str2):
                if str1[i - 1] == str2[j - 1]:
                    cost = 0
                else:
                    cost = 1
                matrix[j * len_str1 + i] = min(matrix[(j - 1) * len_str1 + i] + 1,
                                               matrix[j * len_str1 + (i - 1)] + 1,
                                               matrix[(j - 1) * len_str1 + (i - 1)] + cost)
    
        return matrix[-1]  # 返回矩阵的最后一个值,也就是编辑距离
    
    print(normal_leven("ert","etn"))

    ==================================================================================================================

    KMP算法:

  • 相关阅读:
    Atitit opencv3.0  3.1 3.2 新特性attilax总结
    Atitit html5.1 新特性attilax总结
    Atitit http2 新特性
    Atitit 大龄软件工程师的出路attilax总结
    Atitit 软件项目系统托盘图标解决方案
    Atitit js canvas的图像处理类库attilax总结与事业
    Atitit 切入一个领域的方法总结 attilax这里,机器学习为例子
    css知多少(8)——float上篇
    css知多少(7)——盒子模型
    css知多少(6)——选择器的优先级
  • 原文地址:https://www.cnblogs.com/sherry-yang/p/9330342.html
Copyright © 2011-2022 走看看