【数据结构与算法】task4 散列表(哈希表)&字符串

散列表(哈希表)

实现一个基于链表法解决冲突问题的散列表

参考:https://blog.csdn.net/qq_36047533/article/details/89341156

# -*- coding: utf-8 -*-
"""
Created on Tue Apr 16 21:06:20 2019

@author: janti
"""
class Node:
    def __init__(self,key,value):
        self.key=key
        self.value=value
        self.next=None
        

class ChainHash:
    def __init__(self,capacity):
         self.capacity=capacity
         self.table=[None]*capacity
    def buildHash(self,lista):
        for i in range(len(lista)):
            value=int(lista[i])
            key=value % 13
            print(key)
            node_=self.table[key]
        
            if node_ is None:
                self.table[key]=Node(key,value)
            else:
                while node_.next is not None:
                    if node_.key == key:
                        node_.value = value
                        return
                    node_ = node_.next
                node_.next = Node(key, value)
        
    
        
    def InsertHash(self,value):
        key=value % 13
        node_=self.table[key]
        if node_ is None:
            self.table[key]=Node(key,value)
        else:
            while node_.next is not None:
                if node_.key == key:
                    node_.value = value
                    return
                node_ = node_.next
            node_.next = Node(key, value)
            
    def SearchHash(self,key,value):
        node_ = self.table[key]
        while node_ is not None:
            if node_.value == value:
                return node_ # 返回该指针位置
            node_ = node_.next
        return None    # 若没有找到该数值,则返回空
# In[]
if __name__ == '__main__':
    s=ChainHash(20)
    lista=[1,6,11,14,19]
    
    # In[]
    s.buildHash(lista)
        # In[]
    s.InsertHash(27)
#    print(s.table)
     # In[]
    print(s.SearchHash(1,17))
        

实现一个 LRU 缓存淘汰算法

参考:https://www.baidu.com/link?url=bVZACnm8CrXkoy08uhJc1YmEnqJawfk_rnIarVXKBIaRwQhuAjAg6zEfk4KawoAADN7Wh0xV0ohMCZH5Q181YQGtDSpjtjMddvGWyXfO9ve&wd=&eqid=b411b844001b9ed8000000065cdfad67

https://blog.csdn.net/qq_36387683/article/details/82317673

LRU(Least recently used,最近最少使用)算法根据数据的历史访问记录来进行淘汰数据,其核心思想是“如果数据最近被访问过,那么将来被访问的几率也更高”。 

原理: 

利用list记录key的次序,每次set,或get操作将key插入到list首位。 

缓冲区满之后再出现set操作,移除末尾的key。 

key in dict判断key是否出现过

class LRUcache:
    def __init__(self, size=3):
        self.cache = {}
        self.keys = []
        self.size = size

    def get(self, key):
        if key in self.cache:
            self.keys.remove(key)
            self.keys.insert(0, key)
            return self.cache[key]
        else:
            return None

    def set(self, key, value):
        if key in self.cache:
            self.keys.remove(key)
            self.keys.insert(0, key)
            self.cache[key] = value
        elif len(self.keys) == self.size:
            old = self.keys.pop()
            self.cache.pop(old)
            self.keys.insert(0, key)
            self.cache[key] = value
        else:
            self.keys.insert(0, key)
            self.cache[key] = value

if __name__ == '__main__':
    test = LRUcache()
    test.set('a',2)
    test.set('b',2)
    test.set('c',2)
    test.set('d',2)
    test.set('e',2)
    test.set('f',2)
    print(test.get('c'))
    print(test.get('b'))
    print(test.get('a'))

字符串

实现一个字符集,只包含 a~z 这 26 个英文字母的 Trie 树

参考:https://blog.csdn.net/dzysunshine/article/details/88357659

class Trie:
    # word_end = -1
 
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = {}
        self.word_end = -1
 
    def insert(self, word):
        """
        Inserts a word into the trie.
        :type word: str
        :rtype: void
        """
        curNode = self.root
        for c in word:
            if not c in curNode:
                curNode[c] = {}
            curNode = curNode[c]
          
        curNode[self.word_end] = True
 
    def search(self, word):
        """
        Returns if the word is in the trie.
        :type word: str
        :rtype: bool
        """
        curNode = self.root
        for c in word:
            if not c in curNode:
                return False
            curNode = curNode[c]
            
        # Doesn't end here
        if self.word_end not in curNode:
            return False
        
        return True
 
    def startsWith(self, prefix):
        """
        Returns if there is any word in the trie that starts with the given prefix.
        :type prefix: str
        :rtype: bool
        """
        curNode = self.root
        for c in prefix:
            if not c in curNode:
                return False
            curNode = curNode[c]
        
        return True
 
 
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
朴素的字符串匹配算法

实现朴素的字符串匹配算法

参考:https://blog.csdn.net/u010591976/article/details/81869420

https://blog.csdn.net/zhangyu4863/article/details/80447664

https://blog.csdn.net/weixin_33835103/article/details/87578697

算法基本思想:

  • 将搜索词整个后移一位,再从头逐个比较。这样做虽然可行,但是效率很差,因为你要把"搜索位置"移到已经比较过的位置,重比一遍
  • 遇字符不等时将模式串p右移一个字符,再次从p0(重置j = 0 后)开始比较
  • 最坏情况是每趟比较都在最后出现不等,最多比较n-m+1 趟,总比较次数为m*(n-m+1),所以算法时间复杂性为O(m*n)
def nmatching(t, p):
    i, j = 0, 0
    n, m = len(t), len(p)
    while i < n and j < m:
        if t[i] == p[j]:
            i, j = i+1, j+1
        else:
            i, j = i-j+1, 0        #i-j+1是关键,遇字符不等时将模式串t右移一个字符
    if j == m:                     #找到一个匹配,返回索引值
        return i-j
    return -1                       #未找到,返回-1

    # else:
    #     return -1 

t = 'aabaabaabab'
p = 'baab'
print(nmatching(t,p))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值