来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/implement-magic-dictionary 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

设计一个使用单词列表进行初始化的数据结构,单词列表中的单词 互不相同 。 如果给出一个单词,请判定能否只将这个单词中一个字母换成另一个字母,使得所形成的新单词存在于你构建的字典中。
实现 MagicDictionary 类:
MagicDictionary() 初始化对象
void buildDict(String[] dictionary) 使用字符串数组 dictionary 设定该数据结构,dictionary 中的字符串互不相同
bool search(String searchWord) 给定一个字符串 searchWord ,判定能否只将字符串中 一个 字母换成另一个字母,使得所形成的新字符串能够与字典中的任一字符串匹配。如果可以,返回 true ;否则,返回 false 。

解答

  1. var MagicDictionary = function() {
  2. this.dict = [];
  3. };
  4. /**
  5. * @param {string[]} dictionary
  6. * @return {void}
  7. */
  8. MagicDictionary.prototype.buildDict = function(dictionary) {
  9. this.dict = dictionary;
  10. };
  11. const compare = (source, target, len) => {
  12. let count = 0;
  13. for (let i = 0; i < len; i++) {
  14. if (source[i] !== target[i]) {
  15. ++count;
  16. }
  17. }
  18. return count;
  19. }
  20. /**
  21. * @param {string} searchWord
  22. * @return {boolean}
  23. */
  24. MagicDictionary.prototype.search = function(searchWord) {
  25. const sLength = searchWord.length;
  26. this.dict.forEach(str => {
  27. if (str.length === sLength) {
  28. return compare(str, searchWord, sLength);
  29. }
  30. })
  31. let i = 0,
  32. len = this.dict.length;
  33. while (i < len) {
  34. const str = this.dict[i];
  35. if (str.length === sLength) {
  36. let count = compare(str, searchWord, sLength);
  37. if (count === 1) {
  38. return true;
  39. }
  40. }
  41. ++i;
  42. }
  43. return false;
  44. };
  45. /**
  46. * Your MagicDictionary object will be instantiated and called as such:
  47. * var obj = new MagicDictionary()
  48. * obj.buildDict(dictionary)
  49. * var param_2 = obj.search(searchWord)
  50. */