博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
word ladder-leetcode
阅读量:6173 次
发布时间:2019-06-21

本文共 2476 字,大约阅读时间需要 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 transformed word must exist in the word list. Note that beginWord is not a transformed word.

For example,

Given:

beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]

As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",

return its length 5.

Note:

  • Return 0 if there is no such transform
    • ation sequence.
    • All words have the same length.
    • All words contain only lowercase alphabetic characters.
    • You may assume no duplicates in the word list.
    • You may assume beginWord and endWord are non-empty and are not the same.

     

    UPDATE (2017/1/20):

    The wordList parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

    package tecent;import java.util.HashSet;import java.util.Scanner;import java.util.Set;public class Main3 {        public static void main(String args[]){        Scanner sc = new Scanner(System.in);        String begin =sc.nextLine();        String end = sc.nextLine();        Set
    wordList = new HashSet<>(); String list = sc.nextLine(); String [] word = list.split(" "); for(int i=0;i
    wordList) { // if(!wordList.contains(beginWord)||!wordList.contains(endWord)) return 0; Set
    beginSet = new HashSet
    (), endSet = new HashSet
    (); int len = 1; int strLen = beginWord.length(); HashSet
    visited = new HashSet
    (); beginSet.add(beginWord); endSet.add(endWord); while (!beginSet.isEmpty() && !endSet.isEmpty()) { if (beginSet.size() > endSet.size()) { Set
    set = beginSet; beginSet = endSet; endSet = set; } Set
    temp = new HashSet
    (); for (String word : beginSet) { char[] chs = word.toCharArray(); for (int i = 0; i < chs.length; i++) { for (char c = 'a'; c <= 'z'; c++) { char old = chs[i]; chs[i] = c; String target = String.valueOf(chs); if (endSet.contains(target)) { return len + 1; } if (!visited.contains(target) && wordList.contains(target)) { temp.add(target); visited.add(target); } chs[i] = old; } } } beginSet = temp; len++; } return 0; } }

     

 

转载于:https://www.cnblogs.com/CongLollipop/p/6662440.html

你可能感兴趣的文章
C#设计模式之装饰者
查看>>
[noip模拟20170921]模版题
查看>>
获取ip
查看>>
Spring Shell简单应用
查看>>
移动app可开发的意见于分析
查看>>
周总结7
查看>>
类似OutLook布局的开源控件XPanderControls
查看>>
Web前端工程师成长之路——知识汇总
查看>>
[2018-9-4T2]探索黑暗dark
查看>>
【学术信息】中科院2019年学术期刊分区-综合性期刊
查看>>
ShareObject离线存储相关
查看>>
C++ XML
查看>>
windows批处理 打开exe后关闭cmd
查看>>
Flask开发系列之快速入门
查看>>
关于SaveChanges
查看>>
php7扩展开发 一 获取参数
查看>>
处女座与复读机
查看>>
Laravel 5.2数据库--迁移migration
查看>>
ExtJs Extender controls 不错的例子
查看>>
html的基础知识
查看>>