算法背点板子,随缘更新吧,遇到了可能觉得有意义的就粘上来

  1. kmp算法中,求子串的next数组
        def calc_max_match(self,s:str) -> List[int]:
            match = [0]*len(s)
            c = 0
            for i in range(1,len(s)):
                v = s[i]
                while c and s[c] != v:
                    c = match[c-1]
                if s[c] == v:
                    c+=1
                match[i] = c
            return match
  2. kmp算法中,计算s串中,t串出现了几次/s串分割出t串能有几种方式 
       def kmp_search(self,text:str,pattern:str)-> int:
            match = self.calc_max_match(pattern)
    
            match_cnt = c = 0
    
            for i,v in enumerate(text):
                v = text[i]
                while c and pattern[c] !=v:
                    c = match[c-1]
                if pattern[c] == v:
                    c+=1
                if c == len(pattern):
                    match_cnt+=1
                    c = match[c-1]
            return match_cnt
  3. 动态规划中,状态转移方程计算时的矩阵乘法,代码示例(以二阶方阵为例)
        def multiply(self,a:List[List[int]],b:List[List[int]]):
    
            c = [[0,0],[0,0]]
            for i in range(2):
                for j in range(2):
                    c[i][j] = (a[i][0]*b[0][j]+a[i][1]*b[1][j])%(10**9+7)
            return c
  4. 在计算矩阵的k次幂时,可以通过类似二分的方式简化计算,称为矩阵的快速幂
        def fast_pow(self,a:List[List[int]],n:int) ->List[List[int]]:
            res = [[1,0],[0,1]]
            while n:
                if n%2 :
                    res = self.multiply(res,a)
                a = self.multiply(a,a)
                n //=2
            return res

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值