(LeetCode)字符串

1. 实现 Trie (前缀树)

208. implement-trie-prefix-tree
在这里插入图片描述

class Trie(object):

    def __init__(self):
        """
        Initialize your data structure here.

        用dict嵌套构造字典树
        如果一个节点包含空的子节点, 说明其可以作为终止符
        """
        self.tree = {}


    def insert(self, word):
        """
        Inserts a word into the trie.
        :type word: str
        :rtype: None
        """
        node = self.tree
        for char in word:
            if char not in node:
                node[char] = {}
            node = node[char]
        node[None] = None


    def search(self, word):
        """
        Returns if the word is in the trie.
        :type word: str
        :rtype: bool
        """
        node  = self.tree
        for char in word:
            if char not in node:
                return False
            node = node[char]
        return True if None in node else False


    def startsWith(self, prefix):
        """
        Returns if there is any word in the trie that starts with the given prefix.
        :type prefix: str
        :rtype: bool
        """
        node  = self.tree
        for char in prefix:
            if char not in node:
                return False
            node = node[char]
        return True

2. 回文子串

647. palindromic-substrings
在这里插入图片描述

class Solution(object):
    def countSubstrings(self, s):
        """
        :type s: str
        :rtype: int

        笨办法
            暴力搜索所有可能的子串, 逐个判断是否是回文串
        
        聪明解法
            中心扩展法
            长度为N的字符串的回文子串中心有2N-1个, 
            比如 abc 的回文子串可能的中心有a, b, c, ab之间, bc之间
            对每个中心, 向外扩展, 统计其所有的回文子串数量

            马拉车算法, 对中心扩展法的改进, 暂不做掌握
        """
        cnt = 0

        for center in range(2*len(s)-1):
            if center % 2 == 0:  # 偶数, 中心在字母上
                left, right = center / 2, center / 2
            else:  # 奇数, 中心在字母中间
                left, right = center // 2, center // 2 + 1
            while left <= right and left >= 0 and right < len(s) and s[left] == s[right]:  # 向外扩展
                cnt += 1
                left -= 1
                right += 1
        
        return cnt

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值