leetcode 127. 單詞接龍(C++)
給定兩個單詞(beginWord 和 endWord)和一個字典,找到從 beginWord 到 endWord 的最短轉換序列的長度。轉換需遵循如下規則:
- 每次轉換隻能改變一個字母。
- 轉換過程中的中間單詞必須是字典中的單詞。
說明:
- 如果不存在這樣的轉換序列,返回 0。
- 所有單詞具有相同的長度。
- 所有單詞只由小寫字母組成。
- 字典中不存在重複的單詞。
- 你可以假設 beginWord 和 endWord 是非空的,且二者不相同。
示例 1:
輸入: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] 輸出: 5 解釋: 一個最短轉換序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog", 返回它的長度 5。
示例 2:
輸入: beginWord = "hit" endWord = "cog" wordList = ["hot","dot","dog","lot","log"] 輸出: 0 解釋: endWord "cog" 不在字典中,所以無法進行轉換。
C++
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> word;
for (auto s : wordList) {
word.insert(s);
}
if (word.find(endWord) == word.end()) {
return 0;
}
queue<string> que;
que.push(beginWord);
unordered_set<string> visited;
visited.insert(beginWord);
int num = 1;
while (!que.empty()) {
int m = que.size();
for (int i = 0; i < m; i++) {
string str = que.front();
que.pop();
if (str == endWord) {
return num;
}
for (int j = 0; j < str.size(); j++) {
string ss = str;
for (int k = 0; k < 26; k++) {
char c = k + 'a';
if (c != str[j]) {
ss[j] = c;
}
if (word.find(ss) != word.end() && visited.find(ss) == visited.end()) {
visited.insert(ss);
que.push(ss);
}
}
}
}
num++;
}
return 0;
}
};
相關文章
- 【LeetCode】127. 單詞接龍LeetCode
- LeetCode題解:127. 單詞接龍,雙向BFS,JavaScript,詳細註釋LeetCodeJavaScript
- P1019 單詞接龍(dfs)
- LeetCode 單詞拆分LeetCode
- 單詞接龍---快速建圖----雙向BFS(廣度優先遍歷)
- 洛谷題單指南-搜尋-P1019 [NOIP2000 提高組] 單詞接龍
- LeetCode-139-單詞拆分LeetCode
- LeetCode-單詞規律LeetCode
- LeetCode-079-單詞搜尋LeetCode
- LeetCode-290-單詞規律LeetCode
- C++ 統計單詞數C++
- C++原始碼單詞掃描程式(詞法分析)C++原始碼詞法分析
- [LeetCode題解]79. 單詞搜尋LeetCode
- LeetCode-434-字串中的單詞數LeetCode字串
- LeetCode-151-翻轉字串裡的單詞LeetCode字串
- [LeetCode] Short Encoding of Words 單詞集的短編碼LeetCodeEncoding
- LeetCode1160.拼寫單詞(Java+暴力+HashMap)LeetCodeJavaHashMap
- leetcode_58_最後一個單詞的長度_簡單LeetCode
- LeetCode題解(0692):前K個高頻單詞(Python)LeetCodePython
- Leetcode 58. 最後一個單詞的長度LeetCode
- C++謂詞C++
- 每日leetcode——42. 接雨水LeetCode
- 【leetcode 簡單】第十四題 最後一個單詞的長度LeetCode
- [leetcode 30 串聯所有單詞的子串 10ms]LeetCode
- 社群拼團接龍小程式
- LeetCode C++ 204. Count Primes【Math/Hash Table】簡單LeetCodeC++
- LeetCode C++ 441. Arranging Coins【Math/Binary Search】簡單LeetCodeC++
- LeetCode每日一題:反轉字串中的單詞 III(No.557)LeetCode每日一題字串
- LeetCode 3014[輸入單詞需要的最少按鍵次數I]LeetCode
- 【LeetCode】290. Word Pattern 單詞規律(Easy)(JAVA)每日一題LeetCodeJava每日一題
- WPF 做一個超級簡單的 1024 數字接龍游戲
- 單詞
- LeetCode C++ 703. Kth Largest Element in a Stream【Heap/Design】簡單LeetCodeC++
- 橋接模式(c++實現)橋接模式C++
- leetcode刷題之1160拼寫單詞 java題解(超詳細)LeetCodeJava
- LeetCode每日一題: 最後一個單詞的長度(No.58)LeetCode每日一題
- LeetCode題解(0407):接雨水II(Python)LeetCodePython
- 趣味成語接龍游戲裡,如何判斷使用者輸入的成語接龍成功?