博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Word Ladder
阅读量:5108 次
发布时间:2019-06-13

本文共 2433 字,大约阅读时间需要 8 分钟。

Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the word list

For example,

Given:

beginWord = "hit"
endWord = "cog"
wordList = ["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.
      1 public class Solution { 2     public int ladderLength(String beginWord, String endWord, Set
      wordList) { 3 if (wordList.size () == 0) { 4 return 0; 5 } 6 wordList.add(beginWord); 7 wordList.add(endWord); 8 HashSet
      set = new HashSet<>(); 9 Queue
      q = new LinkedList<>();10 set.add(beginWord);11 q.offer(beginWord);12 int length = 1;13 while (!q.isEmpty()) {14 ++length;15 int size = q.size();16 for (int i = 0; i < size; i++) {17 String crt = q.poll();18 for (String next : getNextWords(crt, wordList)) {19 if (set.contains(next)) {20 continue;21 } 22 if (next.equals(endWord)) {23 return length;24 } 25 q.offer(next);26 set.add(next);27 }28 }29 }30 return 0;31 }32 private String replace(String s, int index, char c) {33 char[] chars = s.toCharArray();34 chars[index] = c;35 return new String(chars);36 }37 private ArrayList
      getNextWords(String word, Set
      dict) {38 ArrayList
      nextWords = new ArrayList
      ();39 for (char c = 'a'; c <= 'z'; c++) {40 for (int i = 0; i < word.length(); i++) {41 if (c == word.charAt(i)) {42 continue;43 }44 String nextWord = replace(word, i, c);45 if (dict.contains(nextWord)) {46 nextWords.add(nextWord);47 }48 }49 }50 return nextWords;51 }52 53 }

       

转载于:https://www.cnblogs.com/FLAGyuri/p/5449477.html

你可能感兴趣的文章
python中的赋值与拷贝(浅拷贝与深拷贝)
查看>>
生成器和迭代器
查看>>
透明-------- GridView 背景透明
查看>>
java 调用 bat 如果里面用了第三方命令 dos 窗口没有关闭 解决方法
查看>>
c# 操作xml文件(插入节点、修改、删除)
查看>>
ps 批量处理
查看>>
TSQLTableJSON解析JSON
查看>>
添加git忽略文件
查看>>
WebZine 关于安全的
查看>>
hdu 1239
查看>>
Android实战之 万能的接口回调
查看>>
Set Matrix Zeroes
查看>>
exe文件无法打开
查看>>
Go中的make和new的区别
查看>>
检测浏览器
查看>>
突然感到人生很绝望_
查看>>
Aop切面开发
查看>>
开始Dev之路
查看>>
信管网2012下半年(11月)信息系统项目管理师论文预测与押题
查看>>
solr异常解决
查看>>