- 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
- 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
- 动态规划中,状态转移方程计算时的矩阵乘法,代码示例(以二阶方阵为例)
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
- 在计算矩阵的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
算法背点板子,随缘更新吧,遇到了可能觉得有意义的就粘上来
于 2023-10-23 01:05:16 首次发布