- Only one letter can be changed at a time
- Each intermediate word must exist in the dictionary
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) { // Adopt breath fisrt search return bfs(start, end, dict); } private int bfs(String start, String end, Set<String> dict) { Queue<String> word = new LinkedList<>(); Queue<Integer> length = new LinkedList<>(); word.offer(start); length.offer(2); while (!word.isEmpty()) { String v = word.poll(); int len = length.poll(); for (int i = 0; i < v.length(); i++) { // Note: Adopt character replacement strategy can save much time. for (char c = 'a'; c <= 'z'; c++) { if (v.charAt(i) == c) continue; String w = replace(v, i, c); if (w.equals(end)) return len; if (dict.contains(w)) { word.offer(w); length.offer(len+1); dict.remove(w); } } } } return 0; } private String replace(String s, int index, char c) { char[] chars = s.toCharArray(); chars[index] = c; return new String(chars); } }
No comments:
Post a Comment