首页 > 代码库 > Word Ladder
Word Ladder
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence fromstart to end, such that:
- 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.
答案
public class Solution { public int ladderLength(String start, String end, Set<String> dict) { if(dict==null||dict.size()==0) { return 0; } if(!dict.contains(start)||!dict.contains(end)) { return 0; } if(start==end) { return 1; } LinkedList<String> queue=new LinkedList<String>(); Set<String> visited=new HashSet<String>(dict.size()*2); Map<String,Integer> len=new HashMap<String,Integer>(dict.size()*2); queue.add(start); visited.add(start); len.put(start,1); for(String p=queue.poll();p!=null;p=queue.poll()) { int LEN=len.get(p); for(int i=0;i<p.length();i++) { StringBuilder builder=new StringBuilder(p); for(char c='a';c<='z';c++) { builder.setCharAt(i,c); String dest=builder.toString(); if(dict.contains(dest)&&!visited.contains(dest)) { visited.add(dest); queue.add(dest); len.put(dest,LEN+1); if(dest.equals(end)) { return LEN+1; } } } } } return 0; } }
Word Ladder
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。