1. 程式人生 > >字串演算法 —— 兩字串相同的單詞

字串演算法 —— 兩字串相同的單詞

1. navie:集合 intersect

以集合的形式分別存放兩字串,然後求集合交集。

def common_words_naive(str1, str2):
	str1_set = set(str1.strip().split())
	str2_set = set(str2.strip().split())
	return str1_set & str2_set			# 集合 intersect

>> common_words_naive('I love word', 'I love China')
{'I', 'love'}

2. 使用 hash

  • 根據字串hash演算法,對字串1的單詞分別求其hash值,時間空間複雜度均為 O

    (n)O(n),並將hash值,存放在集合中

  • 遍歷字串2中的單詞,求其hash值,判斷是否在字串1的hash集合中,如果是,則為 common words

    def bkdr_hash(str, seed=131):
        hash = 0
        for s in str:
            hash = hash*seed + ord(s)
        return hash & 0x7fffffff
    

    將字串hash為整數值的方法及其對比見種字串Hash函式比較

    def common_words_hash(str1, str2):
        words = str1.strip().split(' ')
        str1_hashset = set(bkdr_hash(word) for word in words)
        common_words = []
        for word in str2.strip().split(' '):
            if bkdr_hash(word) in str1_hashset:
                common_words.append(word)
        return common_words
        
    >> common_words_hash('I love word', 'I love China')
    {'I', 'love'}
    

references