Word Ladder

注意各种数据结构的特点,删除的时候要注意遍历

 1 public class Solution {
 2     public int ladderLength(String start, String end, HashSet<String> dict) {
 3         // IMPORTANT: Please reset any member data you declared, as
 4         // the same Solution instance will be reused for each test case.
 5         
 6         LinkedList<String> queue = new LinkedList<String>();
 7         int count = 1;
 8         queue.add(start);
 9         
10         while(!queue.isEmpty())
11         {
12             if(queue.contains(end))
13                 return count;
14             LinkedList<String> visited = new LinkedList<String>();
15             while(!queue.isEmpty())
16             {
17                 String tmp = queue.poll();
18                 for(int i=0;i < tmp.length(); i++)
19                 {
20                     for(char j = 'a'; j <= 'z'; j++)
21                     {
22                         char[] mychar = tmp.toCharArray();
23                         mychar[i] = j;
24                         if(dict.contains(String.valueOf(mychar)))
25                         {
26                             dict.remove(String.valueOf(mychar)); 
27                             visited.add(String.valueOf(mychar));
28                         }
29                         
30                     }
31                 }
32                 
33             }
34             queue.addAll(visited);
35             count++;
36         }
37         return 0;
38     }
39     
40     private boolean isladder(String str1, String str2)
41     {
42         if(str1.length() != str2.length())
43             return false;
44         int count = 0;
45         for(int i=0; i<str1.length(); i++)
46             if(str1.charAt(i) != str2.charAt(i))
47                 count++;
48         if(count == 1)
49             return true;
50         return false;
51     }
52 }
原文地址:https://www.cnblogs.com/jasonC/p/3417500.html