Leetcode050--字符串的过渡
来源:互联网 发布:数控车床车圆球g41编程 编辑:程序博客网 时间:2024/06/16 06:41
一、原题
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
- Only one letter can be changed at a time
- 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; }}
阅读全文
1 0
- Leetcode050--字符串的过渡
- LeetCode050 Pow(x, n)
- 单元测试的过渡解决方案
- CSS3的过渡效果
- css3的过渡transition
- CSS3的过渡 transition
- ViewPager的过渡动画
- Activity过渡的动画
- Activity的过渡动画
- Lineage OS 的过渡
- Vue的过渡效果
- 过渡动画的使用
- Vue的过渡效果
- CSS3的过渡效果
- QT4-->QT5的过渡
- 过渡
- 过渡
- 过渡
- MySql数据库-查询、插入数据时转义函数的使用
- eslint — js书写规范
- nyoj 300 (矩阵快速幂)Kiki & Little Kiki 2
- vim搜索结果高亮
- 自动问答系统流程
- Leetcode050--字符串的过渡
- 从ORA-01752的错误,透过现象看本质
- 1809 The MyInteger class (eden)
- 类似通讯录侧边滑动筛选的sidebar
- Unity 协程(coroutine)详细使用
- vim显示行号
- hadoop分布式集群部署
- volatile关键字解析
- 对于斗地主残局,用python实现solver