数据结构与算法:散列表+字符串

【散列表(哈希表)】

  1. 实现一个基于链表法解决冲突问题的散列表
  2. 实现一个 LRU 缓存淘汰算法

  练习:

  1. 两数之和 https://leetcode-cn.com/problems/two-sum/

思路:字典

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dict={}
        for i in range(len(nums)):
            if target-nums[i] not in dict:
                dict[nums[i]]=i
            else:
                return [dict[target-nums[i]], i]

 

【字符串】

  1. 实现一个字符集,只包含 a~z 这 26 个英文字母的 Trie 树
  2. 实现朴素的字符串匹配算法

  练习:

  1. 反转字符串 https://leetcode-cn.com/problems/reverse-string/

  思路:数组

class Solution:
    def reverseString(self, s: List[str]) -> None:
        for i in range(len(s)//2):
            s[i],s[len(s)-i-1]=s[len(s)-i-1],s[i]

 

  2. 翻转字符串里的单词 https://leetcode-cn.com/problems/reverse-words-in-a-string/

  思路:str.split(), 通过指定分隔符对字符串进行切片

class Solution:
    def reverseWords(self, s: str) -> str:
        if s == '':
            return s
        ls = s.split()
        if ls == []:
            return ''
        result = ''
        for i in range(0,len(ls)-1):
            result += ls[len(ls)-1-i]+' '
        result += ls[0]
        return result

 

  3. 字符串转换整数 (atoi) [作为可选] https://leetcode-cn.com/problems/string-to-integer-atoi/

  思路:str.strip(),去除空格

class Solution:
    def myAtoi(self, str: str) -> int:
        #strip()去除空格
        stripS=str.strip()
        if stripS == '' or stripS == '-' or stripS == '+':
            return 0
        s1 = re.match('[^\d]+', (stripS.lstrip('-')).lstrip('+'))
        if s1!=None:
            return 0
        else:
            s1 = re.search('\-*\+*\d+', stripS).group()
        if s1[:2] == '--' or s1[:2]=='-+' or s1[:2]=='++':
            return 0
        result = int(s1)
        if result >0:
            return 2147483647 if result>2147483647 else result
        else:
            return -2147483648 if result<-2147483648 else result    

 

posted @ 2019-05-19 18:19  DeepLearning_Man  阅读(351)  评论(0编辑  收藏  举报