首页 > 编程语言 >#yyds干货盘点# LeetCode程序员面试金典:添加与搜索单词 - 数据结构设计

#yyds干货盘点# LeetCode程序员面试金典:添加与搜索单词 - 数据结构设计

时间:2023-08-09 23:32:31浏览次数:47  
标签:node yyds search word index Trie 金典 addWord LeetCode

题目:

请你设计一个数据结构,支持 添加新单词 和 查找字符串是否与任何先前添加的字符串匹配 。

实现词典类 WordDictionary :

WordDictionary() 初始化词典对象

void addWord(word) 将 word 添加到数据结构中,之后可以对它进行匹配

bool search(word) 如果数据结构中存在字符串与 word 匹配,则返回 true ;否则,返回  false 。word 中可能包含一些 '.' ,每个 . 都可以表示任何一个字母。

 

示例:

输入:

["WordDictionary","addWord","addWord","addWord","search","search","search","search"]

[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]

输出:

[null,null,null,null,false,true,true,true]

解释:

WordDictionary wordDictionary = new WordDictionary();

wordDictionary.addWord("bad");

wordDictionary.addWord("dad");

wordDictionary.addWord("mad");

wordDictionary.search("pad"); // 返回 False

wordDictionary.search("bad"); // 返回 True

wordDictionary.search(".ad"); // 返回 True

wordDictionary.search("b.."); // 返回 True

代码实现:

class WordDictionary {
    private Trie root;

    public WordDictionary() {
        root = new Trie();
    }
    
    public void addWord(String word) {
        root.insert(word);
    }
    
    public boolean search(String word) {
        return dfs(word, 0, root);
    }

    private boolean dfs(String word, int index, Trie node) {
        if (index == word.length()) {
            return node.isEnd();
        }
        char ch = word.charAt(index);
        if (Character.isLetter(ch)) {
            int childIndex = ch - 'a';
            Trie child = node.getChildren()[childIndex];
            if (child != null && dfs(word, index + 1, child)) {
                return true;
            }
        } else {
            for (int i = 0; i < 26; i++) {
                Trie child = node.getChildren()[i];
                if (child != null && dfs(word, index + 1, child)) {
                    return true;
                }
            }
        }
        return false;
    }
}

class Trie {
    private Trie[] children;
    private boolean isEnd;

    public Trie() {
        children = new Trie[26];
        isEnd = false;
    }
    
    public void insert(String word) {
        Trie node = this;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            int index = ch - 'a';
            if (node.children[index] == null) {
                node.children[index] = new Trie();
            }
            node = node.children[index];
        }
        node.isEnd = true;
    }

    public Trie[] getChildren() {
        return children;
    }

    public boolean isEnd() {
        return isEnd;
    }
}

标签:node,yyds,search,word,index,Trie,金典,addWord,LeetCode
From: https://blog.51cto.com/u_13321676/7027073

相关文章

  • LeetCode从算法到算命—1749.任意子数组和的绝对值的最大值
    1749.任意子数组和的绝对值的最大值题目信息给你一个整数数组nums。一个子数组[numsl,numsl+1,...,numsr-1,numsr]的和的绝对值为abs(numsl+numsl+1+...+numsr-1+numsr)。请你找出nums中和的绝对值最大的任意子数组(可能为空),并返回该最大值。abs(x)......
  • 使用golang解决LeetCode热题Hot100(1-10)
    使用golang解决LeetCode热题Hot1001.两数之和https://leetcode.cn/problems/two-sum/题目给定一个整数数组nums和一个整数目标值target,请你在该数组中找出和为目标值target的那两个整数,并返回它们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个......
  • Leetcode刷题记录本
    Leetcode刷题记录本ID:1点击查看代码暴力破解法classSolution(object):deftwoSum(self,nums,target):""":typenums:List[int]:typetarget:int:rtype:List[int]""" #暴力破解法fori......
  • leetcode:下一个排列
     classSolution{public:voidnextPermutation(vector<int>&nums){intn=nums.size();inti=n-2;while(i>=0&&nums[i]>=nums[i+1]){//从后向前,找到第一个降序的,一直升序说明最大i--;}if(i<0......
  • LeetCode -- 127. 单词接龙
     方法一:双向广搜classSolution{public:intladderLength(stringbeginWord,stringendWord,vector<string>&wordList){set<string>se;for(autoit:wordList){se.insert(it);}if(!se.count(en......
  • LeetCode 热题 100 之 240. 搜索二维矩阵 II
    题目编写一个高效的算法来搜索mxn矩阵matrix中的一个目标值target。该矩阵具有以下特性:每行的元素从左到右升序排列。每列的元素从上到下升序排列。示例一输入:matrix=[[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]],target=5......
  • LeetCode 16. 3Sum Closest 双指针+排序
    Givenanintegerarraynumsoflengthnandanintegertarget,findthreeintegersinnumssuchthatthesumisclosesttotarget.Returnthesumofthethreeintegers.Youmayassumethateachinputwouldhaveexactlyonesolution.Solution先将原数组排序,然......
  • #yyds干货盘点# LeetCode程序员面试金典:水壶问题
    1.简述:有两个水壶,容量分别为 jug1Capacity 和jug2Capacity升。水的供应是无限的。确定是否有可能使用这两个壶准确得到 targetCapacity升。如果可以得到 targetCapacity 升水,最后请用以上水壶中的一或两个来盛放取得的 targetCapacity 升水。你可以:装满任意一个水壶清空......
  • LeetCode 周赛上分之旅 #38 结合排序不等式的动态规划
    ⭐️本文已收录到AndroidFamily,技术和职场问题,请关注公众号[彭旭锐]和BaguTreePro知识星球提问。学习数据结构与算法的关键在于掌握问题背后的算法思维框架,你的思考越抽象,它能覆盖的问题域就越广,理解难度也更复杂。在这个专栏里,小彭与你分享每场LeetCode周赛的解题报告,一......
  • LeetCode 周赛上分之旅 # 37 多源 BFS 与连通性问题
    ⭐️本文已收录到AndroidFamily,技术和职场问题,请关注公众号[彭旭锐]和BaguTreePro知识星球提问。学习数据结构与算法的关键在于掌握问题背后的算法思维框架,你的思考越抽象,它能覆盖的问题域就越广,理解难度也更复杂。在这个专栏里,小彭与你分享每场LeetCode周赛的解题报告,一......