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#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式

《C#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式》Markdown凭借简洁的语法、优良的可读性,以及对版本控制系统的高度兼容性,逐渐成为最受欢迎的文档格式... 目录为什么要将文档转换为 Markdown 格式使用工具将 Word 文档转换为 Markdown(.

Python实现自动化Word文档样式复制与内容生成

《Python实现自动化Word文档样式复制与内容生成》在办公自动化领域,高效处理Word文档的样式和内容复制是一个常见需求,本文将展示如何利用Python的python-docx库实现... 目录一、为什么需要自动化 Word 文档处理二、核心功能实现:样式与表格的深度复制1. 表格复制(含样式与内容)2

Python实现一键PDF转Word(附完整代码及详细步骤)

《Python实现一键PDF转Word(附完整代码及详细步骤)》pdf2docx是一个基于Python的第三方库,专门用于将PDF文件转换为可编辑的Word文档,下面我们就来看看如何通过pdf2doc... 目录引言:为什么需要PDF转Word一、pdf2docx介绍1. pdf2docx 是什么2. by

如何Python使用设置word的页边距

《如何Python使用设置word的页边距》在编写或处理Word文档的过程中,页边距是一个不可忽视的排版要素,本文将介绍如何使用Python设置Word文档中各个节的页边距,需要的可以参考下... 目录操作步骤代码示例页边距单位说明应用场景与高级用China编程途小结在编写或处理Word文档的过程中,页边距是一个

Python使用python-docx实现自动化处理Word文档

《Python使用python-docx实现自动化处理Word文档》这篇文章主要为大家展示了Python如何通过代码实现段落样式复制,HTML表格转Word表格以及动态生成可定制化模板的功能,感兴趣的... 目录一、引言二、核心功能模块解析1. 段落样式与图片复制2. html表格转Word表格3. 模板生

Java如何根据word模板导出数据

《Java如何根据word模板导出数据》这篇文章主要为大家详细介绍了Java如何实现根据word模板导出数据,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... pom.XML文件导入依赖 <dependency> <groupId>cn.afterturn</groupId>

Python实现word文档内容智能提取以及合成

《Python实现word文档内容智能提取以及合成》这篇文章主要为大家详细介绍了如何使用Python实现从10个左右的docx文档中抽取内容,再调整语言风格后生成新的文档,感兴趣的小伙伴可以了解一下... 目录核心思路技术路径实现步骤阶段一:准备工作阶段二:内容提取 (python 脚本)阶段三:语言风格调

Java利用docx4j+Freemarker生成word文档

《Java利用docx4j+Freemarker生成word文档》这篇文章主要为大家详细介绍了Java如何利用docx4j+Freemarker生成word文档,文中的示例代码讲解详细,感兴趣的小伙伴... 目录技术方案maven依赖创建模板文件实现代码技术方案Java 1.8 + docx4j + Fr

vue使用docxtemplater导出word

《vue使用docxtemplater导出word》docxtemplater是一种邮件合并工具,以编程方式使用并处理条件、循环,并且可以扩展以插入任何内容,下面我们来看看如何使用docxtempl... 目录docxtemplatervue使用docxtemplater导出word安装常用语法 封装导出方

Java利用poi实现word表格转excel

《Java利用poi实现word表格转excel》这篇文章主要为大家详细介绍了Java如何利用poi实现word表格转excel,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 一、每行对象类需要针对不同的表格进行对应的创建。package org.example.wordToEx