LeetCode 题解(94): Word Ladder

2024-05-28 09:18
文章标签 leetcode 题解 word 94 ladder

本文主要是介绍LeetCode 题解(94): Word Ladder,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

题目:

Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord to endWord, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the dictionary

For example,

Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]

As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

Note:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.
题解:

用BFS + 单Queue + 每次与wordDict比较,C++可以刚刚通过时间测试,java不能通过时间测试。于是网上学来BFS + 双Queue + 每次修改一个字符并与wordDict比较,每次止血比较 stringLength * 26次。

C++版:

class Solution {
public:int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) {if(beginWord == endWord)return 2;if(wordDict.empty())return 0;wordDict.insert(endWord);queue<pair<string, int>> forward;forward.push(pair<string, int>(beginWord, 1));if(wordDict.find(beginWord) != wordDict.end())wordDict.erase(beginWord);while(!forward.empty()) {pair<string, int> front = forward.front();forward.pop();if(front.first == endWord)return front.second;for(unordered_set<string>::iterator iter = wordDict.begin(); iter != wordDict.end(); ) {if(distance(*iter, front.first)) {forward.push(pair<string, int>(*iter, front.second+1));wordDict.erase(iter++);} else {iter++;}}cout << endl;}return 0;}bool distance(const string& a, const string& b) {int diff = 0;for(unsigned int i = 0; i < a.length(); i++) {if(a[i] != b[i])diff++;if(diff > 1)return false;}if(diff == 1)return true;elsereturn false;}
};

Java版:

注意String比较的时候要用.equals()

public class Solution {public int ladderLength(String beginWord, String endWord, Set<String> wordDict) {if(beginWord == null || endWord == null || wordDict.size() == 0)return 0;Queue<String> queue1 = new LinkedList<>();Queue<String> queue2 = new LinkedList<>();queue1.add(beginWord);int distance = 1;while(wordDict.size() != 0 && queue1.size() != 0) {while(queue1.size() != 0) {String current = queue1.poll();for(int i = 0; i < current.length(); i++) {for(char j = 'a'; j <= 'z'; j++) {String temp = current;if(current.charAt(i) == j)continue;StringBuilder newString = new StringBuilder(current);newString.setCharAt(i, j);current = newString.toString();if(current.equals(endWord))return distance + 1;if(wordDict.contains(current)) {queue2.add(current);wordDict.remove(current);}current = temp;}}}distance += 1;queue1.addAll(queue2);queue2.clear();}return 0;}
}

Python版:

注意复制deque的时候要用深copy。import copy

a = copy.copy(b)

from collections import dequeclass Solution:# @param beginWord, a string# @param endWord, a string# @param wordDict, a set<string># @return an integerdef ladderLength(self, beginWord, endWord, wordDict):if beginWord == None or endWord == None or len(wordDict) == 0:return 0q1 = deque()q1.append(beginWord)q2 = deque()distance = 1while len(wordDict) != 0 and len(q1) != 0:while len(q1) != 0:current = q1.pop()for i in range(len(current)):temp = currentfor j in "abcdefghijklmnopqrstuvwxyz":if j == i:continuecurrent = current[0:i] + j + current[i+1:]if current == endWord:return distance + 1if current in wordDict:q2.append(current)wordDict.remove(current)current = tempdistance += 1q1 = copy.copy(q2)q2.clear()return 0


这篇关于LeetCode 题解(94): Word Ladder的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1010150

相关文章

C#使用Spire.Doc for .NET实现HTML转Word的高效方案

《C#使用Spire.Docfor.NET实现HTML转Word的高效方案》在Web开发中,HTML内容的生成与处理是高频需求,然而,当用户需要将HTML页面或动态生成的HTML字符串转换为Wor... 目录引言一、html转Word的典型场景与挑战二、用 Spire.Doc 实现 HTML 转 Word1

Java实现在Word文档中添加文本水印和图片水印的操作指南

《Java实现在Word文档中添加文本水印和图片水印的操作指南》在当今数字时代,文档的自动化处理与安全防护变得尤为重要,无论是为了保护版权、推广品牌,还是为了在文档中加入特定的标识,为Word文档添加... 目录引言Spire.Doc for Java:高效Word文档处理的利器代码实战:使用Java为Wo

使用Python实现Word文档的自动化对比方案

《使用Python实现Word文档的自动化对比方案》我们经常需要比较两个Word文档的版本差异,无论是合同修订、论文修改还是代码文档更新,人工比对不仅效率低下,还容易遗漏关键改动,下面通过一个实际案例... 目录引言一、使用python-docx库解析文档结构二、使用difflib进行差异比对三、高级对比方

Python从Word文档中提取图片并生成PPT的操作代码

《Python从Word文档中提取图片并生成PPT的操作代码》在日常办公场景中,我们经常需要从Word文档中提取图片,并将这些图片整理到PowerPoint幻灯片中,手动完成这一任务既耗时又容易出错,... 目录引言背景与需求解决方案概述代码解析代码核心逻辑说明总结引言在日常办公场景中,我们经常需要从 W

C#高效实现Word文档内容查找与替换的6种方法

《C#高效实现Word文档内容查找与替换的6种方法》在日常文档处理工作中,尤其是面对大型Word文档时,手动查找、替换文本往往既耗时又容易出错,本文整理了C#查找与替换Word内容的6种方法,大家可以... 目录环境准备方法一:查找文本并替换为新文本方法二:使用正则表达式查找并替换文本方法三:将文本替换为图

Java高效实现Word转PDF的完整指南

《Java高效实现Word转PDF的完整指南》这篇文章主要为大家详细介绍了如何用Spire.DocforJava库实现Word到PDF文档的快速转换,并解析其转换选项的灵活配置技巧,希望对大家有所帮助... 目录方法一:三步实现核心功能方法二:高级选项配置性能优化建议方法补充ASPose 实现方案Libre

Python批量替换多个Word文档的多个关键字的方法

《Python批量替换多个Word文档的多个关键字的方法》有时,我们手头上有多个Excel或者Word文件,但是领导突然要求对某几个术语进行批量的修改,你是不是有要崩溃的感觉,所以本文给大家介绍了Py... 目录工具准备先梳理一下思路神奇代码来啦!代码详解激动人心的测试结语嘿,各位小伙伴们,大家好!有没有想

Python实现Word转PDF全攻略(从入门到实战)

《Python实现Word转PDF全攻略(从入门到实战)》在数字化办公场景中,Word文档的跨平台兼容性始终是个难题,而PDF格式凭借所见即所得的特性,已成为文档分发和归档的标准格式,下面小编就来和大... 目录一、为什么需要python处理Word转PDF?二、主流转换方案对比三、五套实战方案详解方案1:

Python清空Word段落样式的三种方法

《Python清空Word段落样式的三种方法》:本文主要介绍如何用python-docx库清空Word段落样式,提供三种方法:设置为Normal样式、清除直接格式、创建新Normal样式,注意需重... 目录方法一:直接设置段落样式为"Normal"方法二:清除所有直接格式设置方法三:创建新的Normal样

SpringBoot+EasyPOI轻松实现Excel和Word导出PDF

《SpringBoot+EasyPOI轻松实现Excel和Word导出PDF》在企业级开发中,将Excel和Word文档导出为PDF是常见需求,本文将结合​​EasyPOI和​​Aspose系列工具实... 目录一、环境准备与依赖配置1.1 方案选型1.2 依赖配置(商业库方案)二、Excel 导出 PDF