字符串暴力搜索算法
字符串暴力搜索(Violent Search)又称穷举搜索,就是从下标0开始,从左到右一个个顺序匹配查找,一直找到n-m处为止,其中n为字符串长度,m为需要搜索的子串长度,最后统计查找到的数量。
需求规则
- 给定一个字符串N(长度为n),在其内查找是否存在子串M(长度为m);
- 采用循环方式从左到右依次检查n-m次,确定子串存在还是不存在。
下图为字符串暴力搜索过程。在提供的长度为n=88的字符串里,搜索字串"China",从下标为i=0开始搜索,一直搜索到n-5 处。
代码实现:
def StrSearch(arr,keys):
i=0
m=len(keys)
n=len(arr)
count=0
while i+m<=n :
j=0
while j<m:
if arr[i+j]!=keys[j]:
break
j+=1
if j==m :
count+=1
i+=1
return count
s1='I am from China. I am a student.I live in Tianjin China.I love Python.Are you from China'
print(len(s1))
keys='China'
r=StrSearch(s1,keys)
print('在字符串里有%s %d个'%(keys,r))
运行结果: