[LeetCode]127.Word Ladder
来源:互联网 发布:天池大数据竞赛官网 编辑:程序博客网 时间:2024/04/30 03:39
题目
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
Only one letter can be changed at a time
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.
分析
广搜
代码
/**------------------------------------ * 日期:2015-02-07 * 作者:SJF0115 * 题目: 127.Word Ladder * 网址:https://oj.leetcode.com/problems/word-ladder/ * 结果:AC * 来源:LeetCode * 博客: ---------------------------------------**/ #include <iostream> #include <cstring> #include <vector> #include <queue> #include <unordered_set> using namespace std; class Solution { public: int ladderLength(string start, string end, unordered_set<string> &dict) { return BFS(start,end,dict); } private: int BFS(string start,string end,unordered_set<string> &dict){ // 存放单词和单词所在层次 queue<pair<string,int> > q; q.push(make_pair(start,1)); unordered_set<string> visited; visited.insert(start); // 广搜 bool found = false; while(!q.empty()){ pair<string,int> cur = q.front(); q.pop(); string word = cur.first; int len = word.size(); // 变换一位字符 for(int i = 0;i < len;++i){ string newWord(word); for(int j = 0;j < 26;++j){ newWord[i] = 'a' + j; if(newWord == end){ found = true; return cur.second+1; }//if // 判断是否在字典中并且是否已经访问过 if(dict.count(newWord) > 0 && visited.count(newWord) == 0){ visited.insert(newWord); q.push(make_pair(newWord,cur.second+1)); }//if }//for }//for }//while if(!found){ return 0; }//if } }; int main(){ Solution s; unordered_set<string> set = {"hot","dot","dog","lot","log"}; //unordered_set<string> set = {"a","b","c"}; string start("hit"); string end("cog"); int result = s.ladderLength(start,end,set); // 输出 cout<<result<<endl; return 0; }
运行时间
0 0
- [LeetCode]127.Word Ladder
- [Leetcode] 127. Word Ladder
- [leetcode] 127.Word Ladder
- Leetcode-127.Word Ladder
- 127. Word Ladder LeetCode
- Leetcode 127. Word Ladder
- LeetCode 127. Word Ladder
- leetcode 127. Word Ladder
- LeetCode 127. Word Ladder
- LeetCode-127.Word Ladder
- Leetcode 127. Word Ladder
- [leetcode] 127. Word Ladder
- [LeetCode] 127. Word Ladder
- 【LeetCode】127. Word Ladder
- LeetCode 127. Word Ladder
- Leetcode-127. Word Ladder
- LeetCode 127. Word Ladder
- Leetcode 127. Word Ladder
- undo异常
- C++:类的设计————构造与析构函数及其动态内存管理
- POJ 3181 Dollar Dayz
- 硬盘相关
- Android中字体颜色大全-146种(完整版)
- [LeetCode]127.Word Ladder
- poj 2528 Mayor's posters 简单离散化+线段树
- 腾讯游戏数据自愈服务方案
- TCP 握手挥手详解
- Uva230
- UIKit基础:1.第一个UIKit程序
- C51回顾五
- 基于boost asio实现的支持ssl的通用socket框架
- lua学习笔记16:table元表详解