127. Word Ladder
2016-06-15 07:49
197 查看
相当于bfs
public int ladderLength(String beginWord, String endWord, Set<String> wordList) { if(beginWord == null || endWord == null || beginWord.length() == 0 || endWord.length() != beginWord.length() || wordList == null) { return 0; } Set<String> visited = new HashSet<String>(); visited.add(beginWord); wordList.add(endWord); int length = 1; while(!visited.contains(endWord)) { length++; Set<String> currentWord = new HashSet<String>(); for(String word: visited) { for(int i = 0; i < word.length(); i++) { for(char j = 'a'; j <= 'z'; j++) { char[] wordArr = word.toCharArray(); wordArr[i] = j; String curWord = new String(wordArr); if(!curWord.equals(word) && wordList.contains(curWord)) { currentWord.add(curWord); wordList.remove(curWord); } } } } if(currentWord.isEmpty()) { return 0; } visited = currentWord; } return length; }
相关文章推荐
- 像素
- bzoj3926: [Zjoi2015]诸神眷顾的幻想乡 对[广义后缀自动机]的一些理解
- cordova platform add specified version
- my own objective of keras
- Android_eclispe的单词提示
- 面试题--HashMap详解
- AF_DataRequest详解
- poj_2506
- 依赖库
- 同步/异步 阻塞/非阻塞
- 浅谈iOS开发中方法延迟执行的几种方式
- LINUX设备驱动之platform总线
- 【MyBatis学习11】MyBatis中的延迟加载
- Lightoj 1011 - Marriage Ceremonies
- 初次接触zstack
- Linux--内核Uevent事件机制 与 Input子系统
- 关于Fragment你所需知道的一切
- Android之Activity(一):活动简介
- python常用技巧
- USB OTG原理+ ID 检测原理