Leetcode050--字符串的过渡

来源:互联网 发布:数控车床车圆球g41编程 编辑:程序博客网 时间:2024/06/16 01:21

一、原题



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 length5.

Note:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.



二、中文



给出一个开头字符串和一个结尾字符串还有一个字典,然后从字典中查询字符串,每次只能变换一个字母,问一共需要经历多少次才可以



三、举例



开始字符串 ="hit"
结尾字符串 ="cog"
字典 =["hot","dot","dog","lot","log"]

一个转移序列为 "hit" -> "hot" -> "dot" -> "dog" -> "cog",
返回的长度是 5 



四、思路



首先定义一个函数,判断两个字符串之间是否是相差一个字母,然后定义一个队列,从开始字符串开始进行字典的遍历比较,如果在字典中找到相差一个字母的字符串,那么就可以入队列了,然后将该字符串从字典中移除,最后得到的队列就是我们想要寻找的过程


五、程序


import java.util.*;public class Solution {    public int ladderLength(String start, String end, HashSet<String> dict) {        int res = 1;        LinkedList<String> queue = new LinkedList();        queue.offer(start);        while(!queue.isEmpty()){            int size = queue.size();            while(size > 0){                String s = queue.poll();                size--;                                if(isDiffone(s, end)){                    return res + 1;                }                for(Iterator<String> it=dict.iterator();it.hasNext();){                    String str = it.next();                    if(isDiffone(str, s)){                        queue.offer(str);                        it.remove();                    }                }            }            res++;        }        return 0;    }        public boolean isDiffone(String str1, String str2){        int count = 0;        for(int i = 0; i < str1.length(); i++){            if(str1.charAt(i) != str2.charAt(i)){                count++;            }        }        return (count == 1) ? true : false;    }}


原创粉丝点击