zoukankan      html  css  js  c++  java
  • 四指针法

    str1 = '666python6666sdafagagsdgas'
    str2 = '3333python6'
    # 要求两个字符串中的相同部分,我们先用常规的思路实现,然后再用经典的四指针法
    
    # 常规思路是我们将字符串中的每一块都切割出来然后与str1进行比较
    def check(str1,str2):
        maxLenth = 0
        result = ''
        # 将str2中的所有可能重合的字符进行切割
        for start in range(len(str2)):
            for end in range(len(str2)):
                # 获取到每一次切割后的字符
                cutting = str2[start:end+1]
                # 进行查找如果str1中也含有这个字符并且这个字符长度比之前的大那么重新赋值
                if str1.find(cutting) != -1 and len(cutting) > maxLenth:
                    maxLenth = len(cutting)
                    result = cutting
        return result,maxLenth
    
    # print(check(str1,str2))
    # result:('python6', 7)
    
    
    # 第二种四指针法,这是一种非常经典的算法
    
    def PointerCheck(str1,str2):
        maxLenth = 0
        result = ''
        # 将四个指针声明完毕
        a = 0
        b = 0
        c = 0
        d = 0
        # 我们假设ab两个指针指向str1,假设cd两个指针指向str2
        while 1:
            # 当ac指针指向的字符不相同时我们就要移动cd的指针进行再度匹配
            if str1[a] != str2[c]:
                c += 1
                d += 1
            else:
                # 当ac相同时,我们就要移动bd的指针进行最大字符范围的匹配
                while 1:
                    # 当两个字符相同时,指针继续后移
                    if str1[b] == str2[d]:
                        b += 1
                        d += 1
                        # 当匹配的字符大maxLenth时进行返回结果的重置
                        if len(str1[a:b]) > maxLenth:
                            maxLenth = len(str1[a:b])
                            result = str1[a:b]
                    # 当两个字符不相同时,我们移动a指针,并且还原c指针
                    else:
                        a += 1
                        b = a + 1
                        c = 0
                        d =  1
                        break
                     # 当bd指针超出范围是我们结束循环
                    if b >= len(str1) or d >= len(str2):
                        break
            if c >= len(str2) or d >= len(str2):
                c= 0
                d = 1
                a += 1
                b = a + 1
            if a >= len(str1):
                break
        return result, maxLenth
    
    # 第一种算法是将str2的每种字符可能进行切割,而四指针法则是将str1的每种可能进行切割,然后利用指针进行对比
    
    print(PointerCheck(str1,str2))
  • 相关阅读:
    Eclipse for j2ee 无法调式问题
    Windows Redis安装,Java操作Redis
    Java Junit单元测试
    Spring 学习总结 使用静态工厂创建Bean
    JQuery AJAX 解析获得的JSON数据
    Spring中的ApplicationContext事件机制
    Android 扫一扫----ZXing 的使用
    Window环境下 Git 下载Android源码
    JAVA单向/双向链表的实现
    Activity和Service是否是在同一个进程中运行。
  • 原文地址:https://www.cnblogs.com/tengx/p/11758769.html
Copyright © 2011-2022 走看看