Leetcode 127(Java)
来源:互联网 发布:nginx rtmp hls 编辑:程序博客网 时间:2024/05/20 03:06
虽然这道题目有些问题,但是的确帮助我加深了对BFS的理解。在网上看了许多解答以后自己写了答案,有什么可以改进或者考虑不周的地方希望指出。 一开始把单词想象成分散的结点,可以确定的是,beginWord是根结点,endWord是叶子结点,现在要通过其他分散的结点连一条最短路径将他们连接。即转化为树的最小层数问题,用广度优先是比较合理的。AC:
public int ladderLength(String beginWord, String endWord, List<String> wordList) { Queue<String> queue = new LinkedList<>(); //Integer代表了步骤数(树的深度) HashMap<String,Integer> map = new HashMap<>(); //将beginword放入queue与map中 queue.offer(beginWord); map.put(beginWord, 1); while(queue!=null&&queue.size()!=0&&wordList.size()!=0){ String comparation = queue.poll(); StringBuilder str; int length = comparation.length(); int level = map.get(comparation); for(int i=0;i<length;i++){ str = new StringBuilder(comparation); for(char ch='a';ch<='z';ch++){ str.setCharAt(i, ch); String com = str.toString(); if(com.equals(comparation)){ continue; } if(com.equals(endWord)){ return level+1; } if(wordList.contains(com)){ queue.offer(com); wordList.remove(com); map.put(com, level+1); } } } } return 0; }
0 0
- Leetcode 127(Java)
- [leetcode-127]Word Ladder(java)
- Leetcode(java)
- leetcode java
- [LeetCode]Next Permutation java leetcode
- LeetCode: Two Sum (Java)
- [Leetcode] Two Sum (Java)
- [Leetcode] ZigZag Conversion (Java)
- [Leetcode] Reverse Integer (Java)
- [Leetcode] Palindrome Number (Java)
- [Leetcode] Valid Parentheses (Java)
- [Leetcode] Generate Parentheses (Java)
- [Leetcode] Remove Element (Java)
- [Leetcode] Implement strStr() (Java)
- [Leetcode] Next Permutation (Java)
- [Leetcode] Valid Sudoku (Java)
- [Leetcode] Sudoku Solver (Java)
- [Leetcode] Combination Sum (Java)
- css3动画(图片翻转)
- CSS实现列表li边框重合问题
- java类的加载过程和访问权限
- titanic版本二代码注释
- spring转发和重定向
- Leetcode 127(Java)
- [BZOJ3706]反色刷(并查集+欧拉图)
- SpringMVC最小demo创建
- Algorithm Gossip (15) 筛选求质数(Eratosthenes )
- java 线程池的个人记录
- 飞机大战
- Javaの值传递和引用传递
- linux之守护进程与操作编程
- AtCoder 2286 C