Commit 088b5c22 authored by zhayao's avatar zhayao
Browse files

keep going

parent 92a19242
using namespace std;
#include <iostream>
#include <string>
#include <unordered_set>
#include <vector>
#include <queue>
// 1. Two Sum
// solution 1
// O(n^2)时间,double for loop
......@@ -583,8 +591,8 @@ public:
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* ListNode *next;
* };
*/
class Solution {
......@@ -607,7 +615,38 @@ public:
};
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
std::unordered_set<std::string> words(wordList.begin(), wordList.end());
if(words.find(endWord) == words.end()) return 0;
queue<string> q;
q.push(beginWord);
int level = 0;
while(!q.empty()){
int end = q.size();
for(int i=0; i<end; i++){
string current = q.front();
q.pop();
if (current == endWord) return level+1;
words.erase(current);
for(int pos=0; pos<current.size(); pos++){
string new_current = current;
for(char letter='a'; letter<='z'; letter++){
new_current[pos] = letter;
if(words.find(new_current) != words.end()){
q.push(new_current);
}
}
}
}
level++;
}
}
};
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment