Word Ladder----leetcode

来源:互联网 发布:程序员培训 编辑:程序博客网 时间:2024/06/06 00:22

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.

题目大意:就是通过一个字典找到两个字符串的最短变换路径长度,start字符串和end字符串不要求属于字典,但是变换的中间字符串必须存在于字典并且只能出现一次(很关键,题目中没有明显表述,但是确实是如此),每次变换只能改变字符串中的一个单词,这里所有的讨论包括字典都只考虑小写字母。

是广度搜索(BFS)的变型,可以进行一层的搜索,distance加1,直到找到end为止。代码如下:

public class Solution {    public int ladderLength(String start, String end, HashSet<String> dict) {        HashSet<String> set=new HashSet<String>();        Queue<String> queue=new LinkedList<String>();        queue.offer(start);        set.add(start);        int distance=1;        while(!queue.isEmpty())        {            int count=queue.size();            while(count>0)            {                char[] tempstr=queue.poll().toCharArray();                for(int i=0;i<tempstr.length;i++)                {                    char tempchar=tempstr[i];                    for(char c='a';c<='z';c++)                    {                        if(c==tempchar)                            continue;                        tempstr[i]=c;                        String str=new String(tempstr);                        if(str.equals(end))                             return distance+1;                        if(dict.contains(str)&&!set.contains(str))                        {                            queue.offer(str);                            set.add(str);                        }                    }                    tempstr[i]=tempchar;                }                count--;            }            distance++;        }       return 0;     }}


0 0
原创粉丝点击