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:

  1. Only one letter can be changed at a time
  2. 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.

Note:

    • Return 0 if there is no such transformation sequence.
    • All words have the same length.
    • All words contain only lowercase alphabetic characters.

 

我的代码:

public class Solution {
    public int ladderLength(String start, String end, Set<String> dict) {
        Map<String, Integer> distance = new HashMap<String, Integer>();
        Queue<String> words = new ArrayDeque<String>();
        distance.put(start,1);
        words.add(start);
        while(!words.isEmpty())
        {
            String current = words.remove();
            if(current==end)
                return distance.get(current);
            for(int i=0;i<current.length();i++)
                for(char j='a';j<'z';j++){
                    char[] tmp = current.toCharArray();
                    tmp[i]  = j;
                    String next = new String(tmp);                 //注意,chararray转string不能用chararray.toString()
                    if(next.equals(end))
                        return distance.get(current)+1;
                    else if(dict.contains(next) && !distance.containsKey(next)){
                        words.add(next);
                        distance.put(next, distance.get(current)+1);
                    }
                }
        }
        return 0;
    }
}

 

Notes:

HashMap

遍历:

Map<String, Integer> distance = new HashMap<String, Integer>();

Iterator it = distance.entrySet().iterator;  //此外还有keySet.iterator()和values().iterator

while(it.hasNext()){
    Map.entry result = (Map.entry) it.next();

    Object key = result.getKey();

    Object value = result.getValue();

}

查询Key是否存在:distance.containsKey(key)  //或containsValue(value)查询值是否存在

取对应key的值: distance.get(key)

存入键值对: distance.put(key,value)

删除某键(值对):distance.remove(key)

size: distance.size()

是否为空:distance.isEmpty()

 

posted on 2014-12-03 17:20  Jack_Cheng  阅读(108)  评论(0)    收藏  举报