leetcode_wordladder

题目描述

Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord to endWord, 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 length 5.

解题分析

此题总体思路是广度优先BFS搜索,利用队列可进行,但是几次尝试都超时:

  • 首先我利用关系矩阵表示图关系,这样TLE,分析也可看到N*N的复杂度。
  • 后来利用邻接表方式表示,注意到这里小写字母只有26个,又题目说明字符串长度相同,则边的数目最大L*26,邻接表遍历搜索就很快N*L*26,但是建立邻接表的过程还是N*N,依然TLE,尝试发现对于大数据邻接表建立的过程中就超时了。
  • 最后依然是利用边数目有限的思想,由一个单词直接去生成可达单词然后判断是否在字典中,这样就不需要生成邻接表了,这里我由于最初数据处理使用了Linkedlist,使得在判断是否属于候选集的时候也就是contain object的时候费时,TLE,最后使用set结构,终于ac。
  • 回顾很多知识点,BFS和队列,矩阵和邻接表,java的 set 和 collection, java的queue接口一般由linkedlist实现

详细代码

public class Solution {
public int ladderLength(String beginWord, String endWord, Set<String> wordDict) {

     wordDict.add(endWord);
     wordDict.add(endWord);

     Queue<NodeString> queue = new LinkedList<NodeString>();
     queue.add(new NodeString(beginWord, 1));
     wordDict.remove(beginWord);

     while(!queue.isEmpty())
     {
          NodeString current = queue.poll();
          if(current.string.equals(endWord))
          {
              return current.deep;
          }
          else 
          {
            String tmp = current.string;//取点 找临街的表,这里借助最大固定数目的变数来计算而非常规利用矩阵

            for(int i=0;i<tmp.length();i++)
            {
                for(char c='a';c<='z';c++)
                {
                    if(c==tmp.charAt(i))
                    {
                        continue;
                    }
                    else 
                    {
                        char cc[] = tmp.toCharArray();
                        cc[i] = c;
                        String s = new String(cc);
                        if(wordDict.contains(s))
                        {
                            queue.add(new NodeString(s, current.deep+1));
                            wordDict.remove(s);
                        }
                    }
                }
            }
         }

     }
  return 0;
 }

 class  NodeString
 {
     String string;
     int deep;
     public NodeString(String string , int deep)
     {
         this.string = string;
         this.deep = deep;
     }
 }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值