Leetcode211. Add and Search Word - Data structure design

Design a data structure that supports the following two operations:

void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.

For example:

addWord(“bad”)
addWord(“dad”)
addWord(“mad”)
search(“pad”) -> false
search(“bad”) -> true
search(“.ad”) -> true
search(“b..”) -> true
Note:
You may assume that all words are consist of lowercase letters a-z.

题目大意就是实现字典树的查找,多了一个 “.”的匹配


class WordDictionaryNode {

    public WordDictionaryNode[] children;

    public char data;

    public int freq;

    public WordDictionaryNode() {
        children = new WordDictionaryNode[26];
        freq = 0;
    }

}

public class WordDictionary{

    private WordDictionaryNode root;

    public WordDictionary(){
        root=new WordDictionaryNode();
    }
    public void addWord(String word){
        if(word.length()==0){
            return;
        }
        addWord(root,word.toLowerCase().toCharArray(),0);
    }
    private void addWord(WordDictionaryNode rootNode,char[]charArray,int index){

        int k=charArray[index]-'a';
        if(k<0||k>25){
            throw new RuntimeException("charArray[index] is not a alphabet!");
        }
        if(rootNode.children[k]==null){
            rootNode.children[k]=new WordDictionaryNode();
            rootNode.children[k].data=charArray[index];
        }

        if(index==charArray.length-1){
            rootNode.children[k].freq++;
            return;
        }else{
            addWord(rootNode.children[k],charArray,index+1);
        }

    }
    public boolean search(String word){
        if(word.length()==0){
            return false;
        }
        return search(root, word.toCharArray(), 0);
    }
    public boolean search(WordDictionaryNode rootNode,char[]charArray,int index){
        int k=charArray[index]-'a';
        if(k!=-51&&(k<0||k>25)){
            throw new RuntimeException("charArray[index] is not a alphabet!");
        }
        if (k==-51){
            if (index == charArray.length - 1) {
                for (WordDictionaryNode tmp:rootNode.children){
                    if (tmp!=null&&tmp.freq>0) return true;
                }
                return false;
            }
            boolean flag = false;
            for (WordDictionaryNode tmp:rootNode.children) {
                if (tmp!=null) {
                    flag = search(tmp, charArray, index + 1);
                    if (flag) break;
                }
            }
            return flag;
        }
        else {
            if (rootNode.children[k] == null) {
                return false;
            }
            if (index == charArray.length - 1) {
                if (rootNode.children[k].freq>0) return true;
                else return false;
            }
            return search(rootNode.children[k], charArray, index + 1);
        }
    }
}//构造点
class WordDictionaryNode {

    public WordDictionaryNode[] children;

    public char data;

    public int freq;//记录出现的频率

    public WordDictionaryNode() {
        children = new WordDictionaryNode[26];//因为题目中说都是小写
        freq = 0;
    }

}

public class WordDictionary{

    private WordDictionaryNode root;

    public WordDictionary(){
        root=new WordDictionaryNode();
    }
    public void addWord(String word){
        if(word.length()==0){
            return;
        }
        addWord(root,word.toLowerCase().toCharArray(),0);
    }
    private void addWord(WordDictionaryNode rootNode,char[]charArray,int index){

        int k=charArray[index]-'a';
        if(k<0||k>25){
            throw new RuntimeException("charArray[index] is not a alphabet!");
        }
        if(rootNode.children[k]==null){
            rootNode.children[k]=new WordDictionaryNode();
            rootNode.children[k].data=charArray[index];
        }

        if(index==charArray.length-1){
            rootNode.children[k].freq++;
            return;
        }else{
            addWord(rootNode.children[k],charArray,index+1);
        }

    }
    public boolean search(String word){
        if(word.length()==0){
            return false;
        }
        return search(root, word.toCharArray(), 0);
    }
    public boolean search(WordDictionaryNode rootNode,char[]charArray,int index){
        int k=charArray[index]-'a';
        if(k!=-51&&(k<0||k>25)){//.是-51
            throw new RuntimeException("charArray[index] is not a alphabet!");
        }
        if (k==-51){
            if (index == charArray.length - 1) {
                for (WordDictionaryNode tmp:rootNode.children){
                    if (tmp!=null&&tmp.freq>0) return true;//freq>0来保证查找的单词不是之前输入的子串
                }
                return false;
            }
            boolean flag = false;
            for (WordDictionaryNode tmp:rootNode.children) {//当是"."的时候就把这一层都加入
                if (tmp!=null) {
                    flag = search(tmp, charArray, index + 1);
                    if (flag) break;
                }
            }
            return flag;
        }
        else {
            if (rootNode.children[k] == null) {
                return false;
            }
            if (index == charArray.length - 1) {
                if (rootNode.children[k].freq>0) return true;
                else return false;
            }
            return search(rootNode.children[k], charArray, index + 1);
        }
    }
    public static void main(String[] args) {
        WordDictionary wordDictionary = new WordDictionary();
        wordDictionary.addWord("WordDictionary");
        wordDictionary.addWord("addWord");
        wordDictionary.addWord("search");
        System.out.println(wordDictionary.search("addwor"));
    }
}
LeetCode 题目 679 可能是指“两数之和 III - 数据结构设计”(Two Sum III - Data Structure Design)。这是一个数据结构题,要求设计一个支持添加、删除元素以及查找两个整数是否存在目标和的数据结构。具体来说,你需要实现一个名为 `TargetSum` 的类: ```python class TargetSum: def __init__(self): """ Initialize your data structure here. """ self.nums = [] # 用列表存储所有数字 self.sum_map = {} # 使用哈希表 (字典) 存储每个数字的补数及其索引 def add(self, num: int) -> None: """ Adds a new element into the data structure. :param num: An integer :return: None """ self.nums.append(num) if num in self.sum_map: self.sum_map[num].append(len(self.nums)-1) else: self.sum_map[num] = [len(self.nums)-1] def remove(self, val: int) -> None: """ Removes a number from the data structure. :param val: An integer :return: None """ index_to_remove = self.find_index(val) if index_to_remove is not None: self.nums.pop(index_to_remove) for key, indices in self.sum_map.items(): if index_to_remove in indices: indices.remove(index_to_remove) def find(self, target: int) -> bool: """ Returns if there exists any pair of numbers which sum up to the given target. :param target: An integer :return: True if such pair exists, False otherwise. """ return self.has_pair(target) def has_pair(self, target: int) -> bool: """ Internal method used by find() to check for a pair using binary search on nums. """ left, right = 0, len(self.nums)-1 while left < right: current_sum = self.nums[left] + self.nums[right] if current_sum == target: return True elif current_sum < target: left += 1 else: right -= 1 return False ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值