字符串包含问题 python实现
2014-11-10 17:58
501 查看
题目描述:
假设这有一个各种字母组成的字符串A,和另外一个字符串B,字符串里B的字母数相对少一些。什么方法能最快的查出所有小字符串B里的字母在大字符串A里都有?
更详细讲解http://blog.csdn.net/v_july_v/article/details/6347454
方法一:
先排序A,B,然后遍历字符串:
如果遍历完B字符串,则返回true,否则返回false。时间复杂度为O(mlogm)+O(nlogn)+O(m+n)
方法二:利用hash表的方法,时间复杂度为O(n+m)
假设这有一个各种字母组成的字符串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
相关文章推荐
- 字符串包含问题 python实现
- 字符串问题python实现(二)
- 字符串问题python实现(三)
- Python + PHP + RSA 实现加密(解决Python-RSA无法解密一般字符串的问题)
- Python实现判断字符串中包含某个字符的判断函数示例
- 计算4000000000以内最大的f(n)=n的值---字符串问题python实现(五)
- python实现查找文件名包含指定字符串的文件
- python字符串中包含Unicode插入数据库乱码问题 分类: Python 2015-04-28 18:19 342人阅读 评论(0) 收藏
- 字符串问题之串移包含问题<Java实现>
- 左旋转字符串问题 python实现
- python字符串中包含Unicode插入数据库乱码问题
- 计算4000000000内的最大f(n)=n值---字符串的问题python实现(五岁以下儿童)
- Python实现判断一个字符串是否包含子串的方法总结
- python字符串中包含Unicode插入数据库乱码问题
- 常用算法C#实现:字符串包含问题
- 字符串问题python实现(四)
- 字符串问题python实现(一)
- Python实现确认字符串是否包含指定字符串的实例
- python中ljust填充包含中英文字符串问题
- Python实现确认字符串是否包含指定字符串