SpringMVC中請求中文亂碼問題
阿新 • • 發佈:2022-03-17
127. 單詞接龍
字典wordList
中從單詞 beginWord
和 endWord
的 轉換序列 是一個按下述規格形成的序列 beginWord -> s1 -> s2 -> ... -> sk
:
- 每一對相鄰的單詞只差一個字母。
- 對於
1 <= i <= k
時,每個si
都在wordList
中。注意,beginWord
不需要在wordList
中。 sk == endWord
給你兩個單詞 beginWord
和 endWord
和一個字典 wordList
,返回 從 beginWord
到 endWord
的 最短轉換序列 中的 單詞數目
0
。
示例 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" 不在字典中,所以無法進行轉換。
提示:
1 <= beginWord.length <= 10
endWord.length == beginWord.length
1 <= wordList.length <= 5000
wordList[i].length == beginWord.length
-
beginWord
、endWord
和wordList[i]
由小寫英文字母組成 beginWord != endWord
-
wordList
中的所有字串 互不相同
1 #include <iostream> 2 #include <queue> 3 #include <vector> 4#include <unordered_set> 5 #include <string> 6 using namespace std; 7 8 class Solution { 9 public: 10 int ladderLength(string beginWord, string endWord, vector<string>& wordList) { 11 if (beginWord.size() != endWord.size()) { 12 return 0; 13 } 14 if (wordList.size() == 0) { 15 return 0; 16 } 17 unordered_set<string> wordSet(wordList.begin(), wordList.end()); // vector轉換成set,便於bfs時比較後將相鄰元素入棧 18 unordered_set<string> visited; // 已訪問單詞集 19 queue<string> q; 20 q.push(beginWord); 21 int ans = 1; 22 while (!q.empty()) { 23 unsigned int size = q.size(); 24 for (unsigned int i = 0; i < size; i++) { // 逐層遍歷 25 string now = q.front(); 26 q.pop(); 27 for (unsigned int j = 0; j < now.size(); j++) { // 遍歷字元位置 28 string next = now; 29 for (unsigned int k = 0; k < 26; k++) { 30 next[j] = k + 'a'; // 替換某個位置字元 31 if (wordSet.count(next) > 0 && visited.count(next) == 0) { 32 if (next == endWord) { 33 return ans + 1; 34 } 35 q.push(next); 36 visited.emplace(next); 37 } 38 } 39 } 40 } 41 ans++; 42 } 43 return 0; 44 } 45 }; 46 47 int main() 48 { 49 vector<string> wordList = {"hot", "dot", "dog", "lot", "log", "cog"}; 50 string beginWord = "hit"; 51 string endWord = "cog"; 52 Solution *test = new Solution(); 53 cout << test->ladderLength(beginWord, endWord, wordList) << endl; 54 system("pause"); 55 return 0; 56 }