当前位置: 首页 > news >正文

leetcode 127. 单词接龙

题目:127. 单词接龙 - 力扣(LeetCode)

先建立一颗trie树,从beginWord开始bfs;bfs的过程中,对trie树进行dfs寻找“只差一个字母”的其他未遍历到的字符串;直到bfs遍历到endWord。

struct Node {Node** c;string str;bool v = false;Node() {c = (Node**) malloc(26 * sizeof(Node*));memset(c, 0, 26 * sizeof(Node*));}
};
class Solution {
public:void dfs(list<string>& bfs, list<int>& val, const string& s, int path, Node* node, int idx, bool changed) {char c = s[idx] - 'a';Node* t;if (idx == s.length() - 1) {if (changed) {t = node->c[c];if (t && !t->v) {t->v = true;bfs.push_back(t->str);val.push_back(path + 1);}} else {for (int i = 0; i < 26; i++) {if (i == c) continue;t = node->c[i];if (t && !t->v) {t->v = true;bfs.push_back(t->str);val.push_back(path + 1);}}}return;}for (int i = 0; i < 26; i++) {if (!node->c[i]) {continue;}if (i == c) {dfs(bfs, val, s, path, node->c[i], idx + 1, changed);} else if (!changed) {dfs(bfs, val, s, path, node->c[i], idx + 1, true);}}}int ladderLength(string beginWord, string endWord, vector<string>& wordList) {Node* root = new Node;bool hasEndWord = false;char c;Node* t;string s;for (int i = 0; i < wordList.size(); i++) {s = wordList[i];if (s.compare(endWord) == 0) {hasEndWord = true;}t = root;for (int j = 0; j < s.length(); j++) {c = s[j] - 'a';if (!t->c[c]) {t->c[c] = new Node;}t = t->c[c];}t->str = s;}if (!hasEndWord) {return 0;}list<string> bfs;bfs.push_back(beginWord);list<int> val;val.push_back(1);int path;while (!bfs.empty()) {s = bfs.front();bfs.pop_front();path = val.front();val.pop_front();
//            printf("** %s %d\n", s.data(), path);if (s.compare(endWord) == 0) {return path;}dfs(bfs, val, s, path, root, 0, false);}return 0;}
};

http://www.lryc.cn/news/518668.html

相关文章:

  • 如何开发一个支持海量分布式锁的应用库
  • JavaScript系列(17)--类型系统模拟
  • openssl编译
  • 校园网络综合布线系统设计与实践
  • 如果商品信息更新,爬虫会失效吗?
  • 【UE5 C++课程系列笔记】27——多线程基础——ControlFlow插件的基本使用
  • 有收到腾讯委托律师事务所向AppStore投诉带有【水印相机】主标题名称App的开发者吗
  • 标定 3
  • 用 C# 绘制谢尔宾斯基垫片
  • java.lang.NoClassDefFoundError: javax/xml/bind/DatatypeConverter
  • 双因素身份验证技术在NPI区域邮件安全管控上的解决思路
  • java后端对接飞书登陆
  • 记录一次Android Studio的下载、安装、配置
  • 直流无刷电机控制(FOC):电流模式
  • 73.矩阵置零 python
  • 垃圾收集算法
  • SQL-leetcode-262. 行程和用户
  • 太原理工大学软件设计与体系结构 --javaEE
  • Leetcode 139. 单词拆分 动态规划
  • python异常机制
  • 运行爬虫时可能遇到哪些常见问题?
  • BGP与CN2的区别 详解两者在网络传输中的应用与优势
  • Spring 项目 基于 Tomcat容器进行部署
  • “负载均衡”出站的功能、原理与场景案例
  • 02-51单片机数码管与矩阵键盘
  • 不同方式获取音频时长 - python 实现
  • 【python A* pygame 格式化 自定义起点、终点、障碍】
  • 12_Redis发布订阅
  • 归并排序:数据排序的高效之道
  • 【redis初阶】浅谈分布式系统