# -*- coding: utf-8 -*-
'''
Python程序员面试算法宝典---解题总结: 第5章 字符串 5.9 如何实现字符串的匹配
题目:
给定主字符串S与模式字符串P,判断P是否是S的子串,如果是,
那么找出P在S中第一次出现的下标
分析:
举例,S为'abcd',P是'bc',那么P是S的子串;
如果S为'abcd', P是'bca',那么P不是S的子串
和字符串查找相关的问题,想想trie树是否可以完成。
如果是计算前缀是否符合,那可以用trie树。
最简单的方式,设定S的下标i从0开始,设定P的下标j从0开始
遍历i,找到S[i]等于P[j],此时判断
S[i+1] 是否等于P[j+1],如果不等,说明i肯定不是,
令i += 1;
重复上述循环,直到找到
另一种方法:
每次对S[i]进行遍历,判断从S[i]到S[i+len(P) - 1]
这段范围的字符串是否等于P,如果等于找到,
否则令 i+=1
时间复杂度:
O(N*M)
关键:
1 书上解法
字符串匹配用KMP算法
参考:
Python程序员面试算法宝典
'''
def isOk(S, begin, P):
if not S and not P:
return True
elif not S or not P:
return False
lenS = len(S)
lenP = len(P)
for i in range(begin, begin + lenP):
if i >= lenS:
return False
if i - begin >= lenP:
return False
if S[i] != P[i - begin]:
return False
return True
def isSubString(S, P):
if not S and not P:
return 0
elif not S or not P:
return -1
lenS = len(S)
lenP = len(P)
if lenS < lenP:
return False
end = lenS - lenP + 1
for s in range(0, end):
flag = isOk(S, s, P)
if flag:
return s
return -1
def process():
S = "abcd"
P = "bc"
index = isSubString(S, P)
if index >= 0:
print index
else:
print "{P} is not a sub string of {S}".format(
P=P,
S=S
)
S = "abcd"
P = "bca"
index = isSubString(S, P)
if index >= 0:
print index
else:
print "{P} is not a sub string of {S}".format(
P=P,
S=S
)
if __name__ == "__main__":
process()
Python程序员面试算法宝典---解题总结: 第5章 字符串 5.9 如何实现字符串的匹配
猜你喜欢
转载自blog.csdn.net/qingyuanluofeng/article/details/94335654
今日推荐
周排行