字串包含問題 python實現

2021-06-26 22:22:17 字數 2070 閱讀 8129

題目描述:

假設這有乙個各種字母組成的字串a,和另外乙個字串b,字串裡b的字母數相對少一些。什麼方法能最快的查出所有小字串b裡的字母在大字串a裡都有?

更詳細講解

方法一:

先排序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[n]:

s[m],s[n] = s[n],s[m]

if s[md] > s[n]:

s[md],s[n] = s[n],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

字串包含問題

字串包含問題 判斷小字串的所有字元是否大字串都有 思路一 針對小字串的每乙個字元一一與大字串的字元輪詢比較即可,很明顯時間複雜度為o n m bool compare string s1,string s2 if j s2.length return true 思路二 對兩個字串分別排序,同時依次輪...

字串包含問題

假設這有乙個各種字母組成的字串a,和另外乙個字串b,字串裡b的字母數相對少一些。什麼方法能最快的查出所有小字串b裡的字母在大字串a裡都有?比如,如果是下面兩個字串 string 1 abcdefghlmnopqrs string 2 dcgsrqpo 答案是true,所有在string2裡的字母st...

字串包含問題

兩個字串s1和s2,假設s1長度大於等於s2長度,判斷s2是否為s1的乙個子集。例如 s1 abcdefghi,s2 acefg,由於s2中的每個元素都出現在s1中,說明s1包含s2.若s2 acefgk,由於k不在s1中,因此s1不包含s2。設s1長度為m,s2長度為n 方法1 brute for...