2021-08-11 字符串:其它小题

50 阅读1分钟

2021-08-11 字符串:其它小题

反转字符串

class Solution:
    def reverseString(self, s: List[str]) -> None:
    	# 比较简单,题意是想让我们使用双指针。注意一下这里的循环条件就行了
        for i in range(len(s)//2):
            s[i], s[len(s) - 1 - i] = s[len(s) - 1 - i], s[i]

字符串中的第一个唯一字符(有效的字母异位词):同一类题,也是这两种解法比较好

  • 哈希存频率,学习一下库函数的使用:
class Solution:
    def firstUniqChar(self, s: str) -> int:
        frequency = collections.Counter(s)
        for i, ch in enumerate(s):
            if frequency[ch] == 1:
                return i
  • 哈希存索引:
class Solution:
    def firstUniqChar(self, s):
        d = {}
        length = len(s)
        for i in range(length):
            if s[i] not in d:
                d[s[i]] = i
            else:
                d[s[i]] = length + 1
        ret = min(d.values())
        return -1 if ret > length else ret

实现Trie

  • 什么是trie?Trie,又称前缀树或字典树,是一棵有根树,其每个节点包含以下字段:
    在这里插入图片描述
  • 代码实现:
class Trie:
    def __init__(self):
        self.children = [None] * 26
        self.isEnd = False

    def insert(self, word: str) -> None:
        nownode = self
        for ch in word:
            ch = ord(ch)-ord('a')
            if not nownode.children[ch]:
                nownode.children[ch] = Trie()
            nownode = nownode.children[ch]
        nownode.isEnd = True

    def searchPrefix(self, prefix: str) -> "Trie":
        nownode = self
        for ch in prefix:
            ch = ord(ch)-ord("a")
            if not nownode.children[ch]:
                return None
            nownode = nownode.children[ch]
        return nownode

    def search(self, word: str) -> bool:
        tree = self.search(word)
        return tree is not None and tree.isEnd

    def startsWith(self, prefix: str) -> bool:
        return self.searchPrefix(prefix) is not None