1. 程式人生 > >[leetcode] word-ladder

[leetcode] word-ladder

[leetcode] word-ladder

題目描述:
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, 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 length5.

解題思路:
應利用廣度優先遍歷(即樹的的層序遍歷)解決此題。

  1. 定義兩個LinkedList:word存單詞,num記錄更改的次數
  2. 先從word這個linkedList中彈出一個單詞,若彈出的單詞是end單詞,則返回num裡彈出的次數。否則,從第一個字母開始更換a~z中的任意一個字母,若字典中存在新生成的單詞,則將新單詞壓入word中,相應的次數加一壓入num中,並且從字典中刪除這個單詞。

如:
hit 更換第一個字母時,字典裡不包含新生成的所有單詞。在這裡插入圖片描述
同理再更換第二個字母,可以看出字典中包含新單詞hot,則將hot壓入word中,相應的步數加1,壓入num中。
在這裡插入圖片描述

如此替換,直到word裡彈出的是end,返回num中彈出的步數。

程式碼:

import java.util.HashSet;
import java.util.LinkedList;
public class Solution {
    public int ladderLength(String start, String end, HashSet<String> dict) {
        if(start==null||end==null||start.equals(end)){
            return 0;
        }
        int len=start.length();
        LinkedList<String> word=new LinkedList<String>();
        LinkedList<Integer> count=new LinkedList<Integer>();
        
        word.add(start);
        count.add(1);
        
        while(word.size()!=0){
            String curWord=word.pop();
            int curCount=count.pop();
            if(curWord.equals(end)){
                return curCount;
            }
            for(int i=0;i<len;i++){
                char[] curWordChar=curWord.toCharArray();
                for(char c='a';c<='z';c++){
                    curWordChar[i]=c;
                    String newWord=new String(curWordChar);
                    if(dict.contains(newWord)){
                        word.add(newWord);
                        count.add(curCount+1);
                        dict.remove(newWord);
                    }
                }
            }
        }
        return 0;
    }
}

注:
在這裡解釋一下樹的層序遍歷
規則是若數為空,則空操作返回,否則從樹的第一層,也就是根節點開始訪問,從上而下逐層遍歷,在同一層中,按從左到右的順序對節點逐個訪問。