LeetCode-神奇的字典

233 阅读1分钟

算法记录

LeetCode 题目:

  给定一个二叉树(具有根结点 root), 一个目标结点 target ,和一个整数值 K 。返回到目标结点 target 距离为 K所有结点的值的列表。 答案可以以任何顺序返回。


说明

一、题目

  void buildDict(String[] dictionary) 使用字符串数组 dictionary 设定该数据结构,dictionary 中的字符串互不相同

  bool search(String searchWord) 给定一个字符串 searchWord ,判定能否只将字符串中 一个 字母换成另一个字母,使得所形成的新字符串能够与字典中的任一字符串匹配。如果可以,返回 true ;否则,返回 false 。

二、分析

  • 替换一个数可以转换为其他的单词,也就是说转换后的单词在转换位之前和原始单词有着相同的前缀;
  • 字符串的相同前缀问题自然就会转换为字典树的操作,这道题也是字典数的一种用法,字典树额模糊查询,不过模糊的字符只有一个。
class MagicDictionary {
    private Node trie;
    /** Initialize your data structure here. */
    public MagicDictionary() {
        trie = new Node();
    }
    
    public void buildDict(String[] dictionary) {
        for(String s : dictionary) trie.insert(s);
    }
    
    public boolean search(String searchWord) {
        return trie.search(searchWord);
    }
}

class Node{
    public boolean flag;
    public Node[] next;
    public Node() {
        next = new Node[26];
        flag = false;
    }
    public void insert(String s) {
        Node temp = this;
        for(char c : s.toCharArray()) {
            if(temp.next[c - 'a'] == null) temp.next[c - 'a'] = new Node();
            temp = temp.next[c - 'a'];
        }
        temp.flag = true;
    }
    public boolean search(String s) {
        return searchDouble(this, s.toCharArray(), 0, 1);
    }
    public boolean searchDouble(Node root, char[] w, int count, int num) {
        if(root == null) return false;
        if(count == w.length) return num == 0 && root.flag;
        if(root.next[w[count] - 'a'] != null &&
            searchDouble(root.next[w[count] - 'a'], w, count + 1, num)) return true;
        for(int i = 0; i < 26; i++) {
            if(i != w[count] - 'a' && root.next[i] != null &&
                searchDouble(root.next[i], w, count + 1, num - 1)) return true;
        }
        return false;
    }
}

总结

熟悉字典树的结构特点和用法。