您的位置:首页 > 编程语言 > Python开发

字符串包含问题 python实现

2014-11-10 11:30 375 查看
题目描述:


假设这有一个各种字母组成的字符串A,和另外一个字符串B,字符串里B的字母数相对少一些。什么方法能最快的查出所有小字符串B里的字母在大字符串A里都有?

更详细讲解http://blog.csdn.net/v_july_v/article/details/6347454

方法一:

先排序A,B,然后遍历字符串:

while i < lenA and j < lenB:
while A[i] < B[j] and i < lenA-1:
i += 1
if A[i] != B[j]:
break
j += 1


如果遍历完B字符串,则返回true,否则返回false。时间复杂度为O(mlogm)+O(nlogn)+O(m+n)

#!/usr/bin/env python

def partition(s, m, n):
#s is a list
key = s[n-1]
l,r = m,n-2
while True:
while l <= n-2 and s[l] <= key:
l += 1
while r>= m and s[r] > key:
r -= 1
if l < r:
s[l],s[r] = s[r],s[l]
else:
break
s[l],s[n-1] = s[n-1],s[l]
return l

def medin3(s, m, n):
md = m + (n-m)/2
if s[m] > s[md]:
s[m],s[md] = s[md],s[m]
if s[m] > s
:
s[m],s
= s
,s[m]
if s[md] > s
:
s[md],s
= s
,s[md]
s[md],s[n-1] = s[n-1],s[md]
return s[n-1]

def quicksort(s, m, n):
#s is a list
if m < n:
medin3(s, m, n)
k = partition(s, m, n)
quicksort(s, m, k)
quicksort(s, k+1, n)

def isinclude(A, B):
lenA,lenB = len(A),len(B)
quicksort(A, 0, lenA-1)
quicksort(B, 0, lenB-1)
i,j = 0,0
while i < lenA and j < lenB: while A[i] < B[j] and i < lenA-1: i += 1 if A[i] != B[j]: break j += 1
if j == lenB:
return True
else:
return False


方法二:利用hash表的方法,时间复杂度为O(n+m)

def hashmatch(A, B):
myhash = dict.fromkeys(['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'],0)
lenA = len(A)
lenB = len(B)
for i in xrange(lenA):
myhash[A[i]] += 1
for i in xrange(lenB):
if myhash[B[i]] == 0:
return False
else:
myhash[B[i]] -= 1
return True
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: