127. Word Ladder
来源:互联网 发布:java多线程共享数据 编辑:程序博客网 时间:2024/06/05 21:00
单向bfs
方法也是想到和写了出来,就是没有用find这个方法导致超时!!!用了iterator
其实就是bfs不断判断是否是那就ok了,数据结构的使用方法还是有点弱!
class Solution {public: void addnext(string s, queue<string>& qu, unordered_set<string>& wordList){ wordList.erase(s); for(int i = 0; i < s.length(); ++ i){ char temp = s[i]; for(int j = 0; j < 26; ++ j){ s[i] = 'a' + j; if(wordList.find(s) != wordList.end()){ qu.push(s); wordList.erase(s); } } s[i] = temp; } } int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) { wordList.insert(endWord); queue<string>qu; addnext(beginWord, qu, wordList); int sum = 2; while(!qu.empty()){ int n = qu.size(); for(int i = 1; i <= n; ++ i){ string t = qu.front(); qu.pop(); if(t == endWord) return sum; addnext(t, qu, wordList); } sum++; } return 0; }};
双向bfs
双向bfs,比单向更快,没有用queue,用了unorder set一样可以做,每次结束就装换,开两个,一头一尾,这题十分考验打码能力,非思维能力,2刷值得继续练习!
class Solution {public: int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) { unordered_set<string> head, tail, *phead, *ptail; head.insert(beginWord); tail.insert(endWord); int sum = 2; while(!head.empty() && !tail.empty()){ if(head.size() < tail.size()){ phead = &head; ptail = &tail; } else{ phead = &tail; ptail = &head; } unordered_set<string> temp; for(auto it = phead -> begin(); it != phead -> end(); it++){ string word = *it; wordList.erase(word); for(int i = 0; i < word.length(); ++ i){ char t = word[i]; for(int j = 0; j < 26; ++ j){ word[i] = 'a' + j; if(ptail -> find(word) != ptail -> end()) return sum; if(wordList.find(word) != wordList.end()){ temp.insert(word); wordList.erase(word); } } word[i] = t; } } sum++; swap(*phead, temp); } return 0; }};
0 0
- [LeetCode]127.Word Ladder
- [Leetcode] 127. Word Ladder
- 127. Word Ladder
- [leetcode] 127.Word Ladder
- Leetcode-127.Word Ladder
- 127. Word Ladder LeetCode
- Leetcode 127. Word Ladder
- LeetCode 127. Word Ladder
- 127.Word Ladder
- 127. Word Ladder
- leetcode 127. Word Ladder
- 127. Word Ladder
- LeetCode 127. Word Ladder
- LeetCode-127.Word Ladder
- Leetcode 127. Word Ladder
- 127. Word Ladder
- [leetcode] 127. Word Ladder
- 127. Word Ladder (很重要!!!)
- 解决dialog中嵌套EditText,自动弹出软键盘的问题
- 设计模式学习笔记三(行为型模式)
- linux 进度条原理,缓冲区,回车换行
- Qt中QJosn生成与解析
- Windows 10将在4月升级的十个新界面特性
- 127. Word Ladder
- 数据库事务隔离级别
- UML的9种图例解析
- Android技术之 内存泄露
- elasticsearch启动报错的问题解决方法
- java集合之ArrayList和LinkList
- oracle 中 使用 begin end 批量更新,删除资料
- Linux下搭建BT服务器
- Toolbar