计算字符串t在字符串s中出现的次数(KMP)
来源:互联网 发布:slackware安装软件 编辑:程序博客网 时间:2024/05/22 14:35
题意:给出两个字符串s和t,求t在s中出现的个数
思路:用kmp算法,在第一次匹配(t,s)后,如果t的前缀和后缀一样,就可以直接将s移动到与后缀匹配的位置,不必只一位一位的移
代码如下:
def fail(sub_string): ans = [0] * (len(sub_string) + 1) for i in range(1, len(sub_string)): j = ans[i] while j > 0 and sub_string[i] != sub_string[j]: j = ans[j] if sub_string[i] == sub_string[j]: ans[i + 1] = j + 1 else: ans[i + 1] = 0 return ansdef count_substring(string, sub_string): next = fail(sub_string) cnt = 0 start = 0 length = len(string) - len(sub_string) i = 0 while i <= length: while start < len(sub_string) and string[i + start] == sub_string[start]: start = start + 1 if start == len(sub_string): cnt = cnt + 1 i = i + start - next[start] if next[start] == 0: i = i + 1 start = next[start] return cntif __name__ == "__main__": string = input().strip() sub_string = input().strip() count = count_substring(string, sub_string) print(count)
0 0
- 计算字符串t在字符串s中出现的次数(KMP)
- 统计字符串s在字符串str中出现的次数
- ORACLE计算字符在字符串中出现的次数
- 计算字符在字符串中出现的次数
- [SQL]计算字符在字符串中出现的次数
- ORACLE计算字符在字符串中出现的次数
- 计算字符在字符串中出现的次数
- substr_count计算***在某字符串中出现的次数;
- 计算特定字符在字符串中出现的次数
- POJ 3461 Oulipo (KMP字符串匹配·统计p在s中出现次数)
- 计算字符串中出现字符的次数
- 计算字符串中出现字符的次数
- mysql计算字符串在长字符串中出现次数
- 计算字符串出现的次数
- C语言-统计字符串s在字符串str中出现的次数
- C语言-统计字符串s在字符串str中出现的次数
- C# 在一个字符串中,找出出现次数最多的字母,并计算次数?
- 计算某字符串在另外一个字符串中出现的次数
- 单字符I/O:getchar()和putchar()
- NYOJ27水池数目(dfs)
- chmod权限
- git备忘录
- JavaWeb日记——Springboot 热部署的两种方式
- 计算字符串t在字符串s中出现的次数(KMP)
- MySQL查询语句大全
- spring面试题
- 【bzoj3529】[Sdoi2014]数表
- register_chrdev_region
- C语言的赋值表达式返回右值
- WordPress编辑文章时出现的错误
- Companies Using Lisp
- LayoutParams 类型转换异常:java.lang.ClassCastException: android.widget.FrameLayout$LayoutParams