leetcode_wordladder,leetcode

來源:互聯網
上載者:User

leetcode_wordladder,leetcode
題目描述

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;     } }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.