Word Ladder
来源:互联网 发布:山东男人啪的表现知乎 编辑:程序博客网 时间:2024/06/12 02:12
-----QUESTION-----
Given two words (start
- 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.
-----SOLUTION-----
class Solution {public: int ladderLength(string start, string end, unordered_set<string> &dict) { int wordLen = start.length(); int distance = 1; string current; queue<string> queue_to_push; //prepared for next loop queue<string> queue_to_pop; //string to deal in this loop queue_to_pop.push(start); while(!queue_to_pop.empty()) { current = queue_to_pop.front(); queue_to_pop.pop(); for (int i = 0; i < wordLen; i++) for (int j = 'a'; j <= 'z'; j++) { if (j == current[i]) //skip the current character continue; char temp = current[i]; current[i] = j; if(current==end) { return distance+1; } if (dict.count(current) > 0) //exist such a word in the dict { dict.erase(current); //delete such a word queue_to_push.push(current); } current[i] = temp; //restore the string } if(queue_to_pop.empty()) { swap(queue_to_push, queue_to_pop); distance++; } } return 0; //fail to find }};
0 0
- Word Ladder
- Word Ladder
- word ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- Word Ladder
- jquery 监听鼠标点击事件,任意位置,及是否获得焦点
- jQuery提交多个表单的小例子,有需要的朋友可以参考一下
- HDU 2002 计算球体积
- 用GoogleEarth选择遥感分类的训练样区
- poj_2240 Floyd算法变形套现问题
- Word Ladder
- jquery打开页面
- UVA 10905 Children's Game
- 如何让优秀的程序员更上一层楼
- asp.net,cookie,写cookie,取cookie
- Android开发:在EditText中关闭软键盘
- 【Android笔记】Android MediaPlayer的生命周期
- HDU 2004 成绩转换
- 禁止手机浏览器上两个手指触碰在屏幕上,拉大距离,放大页面;缩小距离,缩小页面