版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010412858/article/details/82564294
今天遇到了一个算法题目:相似字符串。题目提出了一个相似字符串的定义:形如“aba”与“xyx”相似;“abc”与“xyz”相似,要求找出输入的两个字符串中相似字符串的个数。
首先我感觉这个有点类似于正则表达式,但需要根据给定的规则匹配出所有的字符串,又有点像KMP算法的过程。
这里给出一个思路:
在“最长公共字符串”这个DP问题中,用了一个矩阵来保存字符比较的状态,但在这个问题中,“aba”与“xyx”没法直接比较,所以我们需要提取它们的共同特征来比较,比如都转化成“0,1,0”的数字就可以直接比较了。
这里给出Python3的实现代码:
#!/bin/python
# -*- coding: utf8 -*-
import sys
import os
import re
#请完成下面这个函数,实现题目要求的功能
#当然,你也可以不按照下面这个模板来作答,完全按照自己的想法来 ^-^
#******************************开始写代码******************************
def str_info(data):
res = []
res_str = []
for i in range(0,len(data)):
if data[i] not in res_str:
res_str.append(data[i])
res.append(i)
else:
res_str.append(data[i])
res.append(data.index(data[i]))
return res
def solve(S, T):
t_res = str_info(T)
count = 0
for i in range(0,len(S)-len(T)+1):
combine = S[i:i+len(T)]
s_res = str_info(combine)
if s_res == t_res:
count +=1
return count
#******************************结束写代码******************************
'''
try:
_S = input()
except:
_S = None
try:
_T = input()
except:
_T = None
'''
# res = solve(_S, _T)
res = solve("ababcb", "xyx")
print(str(res) + "\n")
假设len(string1) = M, len(string2) = N,这个方法的时间复杂度为O(M*N)。
还有一些方法:
作者:上天请赐我一个OFFER
链接:https://www.nowcoder.com/discuss/106200?type=0&order=0&pos=40&page=1
来源:牛客网
def solve(S, T):
if not S or not T:
return 0
if len(S) < len(T):
return 0
count = 0
for i in range(len(S) - len(T) + 1):
if isSomorphic(S[i:i+len(T)], T):
count += 1
return count
def isSomorphic(S, T):
return len(set(S)) == len(set(T)) == len(set(zip(S, T)))