Word Ladder (Java)

来源:互联网 发布:阿里云视频上传api 编辑:程序博客网 时间:2024/06/04 01:17

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:

  1. Only one letter can be changed at a time
  2. 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.
每次变化一个的这种类型的题优先考虑有BFS,每次控制变化其中一个字母,然后和dict中的比较,如果一样就加到树的下一层。count值由层数决定。这道题相当于树的最小深度。
注意char和string的区别,尤其是equals方法和contains方法,编译器不会报错。前后如果一个是字符一个是字符串,即使字符串只含一个字符('b',"b"),也不会相等。
另注意:LinkedList是双链队列,add是加在队尾,push是加在队头,poll和pop都是删队头!
Source
public class Solution {    public int ladderLength(String start, String end, Set<String> dict) {        LinkedList<String> queue = new LinkedList<String>();        queue.add(start);                int count = 1;        int cur = 1;        int next = 0;                while(!queue.isEmpty()){        String a = queue.poll();        if(dict.contains(a)){        dict.remove(a);  //dict里有start的先删除        }        cur --;                        char[] str = a.toCharArray();        for(int i = 0; i < str.length; i++){        char temp = str[i];        for(char j = 'a'; j <= 'z'; j ++){        if(j == temp) continue;  //***        str[i] = j;        String b = new String(str); //注意不是toString 必须要先将str变为string才可以用下面的equals和contains判断        if(b.equals(end)) return ++count; //要写在判断contains之前               if(dict.contains(b)){   //contains                queue.add(b);        next ++;        dict.remove(b);//remove                }                }        str[i] = temp; //变化完记得还原,这样可以保证每次遍历只变了其中一个字母                        }        if(cur == 0){        cur = next;        next = 0;        count ++; //dict一层可能会有多个只变一个元素的  count应该在此处加而非dict.contains里面        }                }        return 0;      }}


Test
    public static void main(String[] args){    Set<String> dict = new HashSet<String>();    dict.add("hot");    dict.add("cog");    dict.add("dot");    dict.add("dog");    dict.add("hit");    dict.add("lot");    dict.add("log");    //dict.add("dot");        System.out.println(new Solution().ladderLength("hit", "cog", dict));    //System.out.println(new Solution().ladderLength("a", "c", dict));        }


0 0