力扣 211. 添加与搜索单词 - 数据结构设计

题目来源:https://leetcode-cn.com/problems/design-add-and-search-words-data-structure/

大致题意:
实现一个词典类:

  • 有构造函数可以初始化
  • 有 addWord(String word) 方法,可以添加一个单词到当前对象
  • 有 search(String word) 方法,搜索当前对象中是否有该单词,若有返回 true,否则返回 false。word 中可能包含一些 ‘.’,每个 ‘.’ 可以表达任意字符

思路

使用前缀树进行单词搜索是一个好方法

前缀树

对于本题,基本的前缀树数据结构就可以解决 addWord 方法
而对于 search 方法,需要考虑到出现 ‘.’ 的情况

  • 搜索过程中,若当前字符为正常的小写字母,那么按照前缀树的搜索方法,即查找当前节点是否存在当前字符的子节点,若有则递归查询下一位;若当前字符为 ‘.’ ,那么就对当前节点的所有非空子节点递归查询下一位

代码:


public class WordDictionary {
    private Trie root;

    public WordDictionary() {
        root = new Trie();
    }
    
    public void addWord(String word) {
        root.insert(word);
    }
    
    public boolean search(String word) {
        return root.search(word);
        // return dfs(word, 0, root);
    }
	// 题解上的方法,dfs
    private boolean dfs(String word, int index, Trie node) {
    	// 已经遍历到最后一个字符对应节点,若当前节点为单词末尾,则表示找到 word
        if (index == word.length()) {
            return node.getIsEnd();
        }
        char ch = word.charAt(index);
        // 如果当前字符为 .
        if (!Character.isLetter(ch)) {
        	// dfs 所有非空子节点
            for (int i = 0; i < 26; i++) {
                Trie child = node.getChildren()[i];
                if (child != null && dfs(word, index + 1, child)) {
                    return true;
                }
            }
        } else {
        	// dfs 当前字符对应的子节点
        	// 如果为空,则会执行末尾语句,返回 false
            int idx = ch - 'a';
            Trie child = node.getChildren()[idx];
            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++) {
            int idx = word.charAt(i) - 'a';
            // 若当前字符对应的子节点为空,则新建该子节点
            if (node.children[idx] == null) {
                node.children[idx] = new Trie();
            }
            node = node.children[idx];
        }
        node.isEnd = true;
    }

    public boolean search(String word) {
        Trie node = this;
        for (int i = 0; i < word.length(); i++) {
        	// 当前字符为正常字符
            if (word.charAt(i) != '.') {
                int idx = word.charAt(i) - 'a';
                // 对应子节点为空,直接返回
                if (node.children[idx] == null) {
                    return false;
                }
                // 递归到子节点
                node = node.children[idx];
            } else {	// 当前字符为 .
            	// 若 . 为最后一个字符
                if (i == word.length() - 1) {
                	// 只要子节点有一个不为空且其为单词末尾,则代表找到当前单词
                    for (int j = 0; j < 26 ; j++) {
                        if (node.children[j] != null && node.children[j].isEnd) {
                            return true;
                        }
                    }
                }
                // 在所有非空子节点中递归查询剩下的字符串
                for (int j = 0; j < 26; j++) {
                    if (node.children[j] != null && node.children[j].search(word.substring(i + 1, word.length()))) {
                        System.out.println(word.substring(i + 1, word.length()));
                        return true;
                    }
                }
                return false;
            }
        }
        return node.isEnd;
    }

    public boolean getIsEnd() {
        return this.isEnd;
    }

    public Trie[] getChildren() {
        return this.children;
    }
}
### 题目描述 给定两个字符串 `text1` 和 `text2`,返回这两个字符串的最长公共子序列的长度。如果不存在公共子序列,返回 0。一个字符串的子序列是指由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。两个字符串的公共子序列是这两个字符串所共同拥有的子序列。例如,输入 `text1 = “abcde”`,`text2 = “ace”`,输出为 3,因为最长公共子序列是 “ace”,它的长度为 3[^1][^4]。 ### 解题思路 - **状态定义**:`dp[i][j]` 中 `i` 表示字符串 1 的前 `i` 个字符,`j` 表示字符串 2 的前 `j` 个字符,`dp[i][j]` 表示 `s1[0…i]` 和 `s2[0…j]` 的最长公共子序列。`dp` 数组大小为 `(len1 + 1) * (len2 + 1)`,其中 `len1` 和 `len2` 分别是两个字符串的长度[^1]。 - **状态转移方程**: - 若 `s1[i - 1] == s2[j - 1]`,则该字符需要添加到最长公共子序列中,`dp[i][j] = dp[i - 1][j - 1] + 1`。 - 若 `s1[i - 1] != s2[j - 1]`,则 `dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])`[^1][^3][^5]。 - **初始化**:`dp[0][j]` 和 `dp[i][0]` 都表示空字符串字符串 `s` 的公共序列,长度设置为 0[^1]。 - **输出**:`dp[len1][len2]` 即为两个字符串的最长公共子序列的长度[^1][^3][^5]。 ### 代码实现 #### C++ 实现 ```cpp class Solution { public: int longestCommonSubsequence(string text1, string text2) { int len1 = text1.size(); int len2 = text2.size(); if(len1 == 0 || len2 == 0) return 0; int dp[len1 + 1][len2 + 1]; memset(dp, 0, sizeof(dp)); for(int i = 1; i <= len1; i++){ for(int j = 1; j <= len2; j++){ if(text1[i - 1] == text2[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1; else dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); } } return dp[len1][len2]; } }; ``` #### Java 实现 ```java import java.util.Arrays; class Solution { public int longestCommonSubsequence(String text1, String text2) { int rows = text1.length() + 1; int cols = text2.length() + 1; int[][] dp = new int[rows][cols]; for (int i = 1; i < rows; i++) { for (int j = 1; j < cols; j++) { if (text1.charAt(i - 1) == text2.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1] + 1; } else { dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); } } } return dp[rows - 1][cols - 1]; } } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三更鬼

谢谢老板!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值