[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.

其实这题可以看成是一个图论里的最短路径问题:把每一个字典里的词都看成一个节点,如果两个词之间能够只通过修改一个字母即可相等,那么就可以认为两个节点相连,而且距离为1。因此,这题可以看做是求一条从start到end的最短路径。注意这里从start到自身的距离应该为1,而不能是0。

这题不能用DP做,因为DP本质是用空间换时间,而这里需要缓存的中间状态实在太多,随着路径长度指数级增长,内存根本不够用。所以这题只要在最基本的BFS和DFS里挑一个就行了。由于这里不是要求所有的路径而是求的最短路径,故应该使用BFS而非DFS。

确定好思路后,可以将BFS所有已经探索到的节点都放到一个HashMap里,key存节点值,即string值,value存距离值。

由于我这里用的Java实现,String类里面没有类似C++里的replace方法,所以自己实现了一个replace方法作为辅助。


	public int ladderLength(String start, String end,
			HashSet dict) {
		Map map = new HashMap();
		Queue queue = new LinkedList();
		queue.offer(start);
		map.put(start, 1);

		while (!queue.isEmpty()) {
			String str = queue.poll();
			int dist = map.get(str);
			if (str.equals(end))
				return dist;

			for (int i = 0; i < str.length(); i++) {
				for (int j = 0; j <= 25; j++) {
					// transform it into another word
					String newStr = replace(str, i, (char) ('a' + j));

					// if a new word is explored
					if (!map.containsKey(newStr) && dict.contains(newStr)) {
						map.put(newStr, dist + 1);
						queue.offer(newStr);
					}
				}
			}
		}
		return 0;
	}

	// replace the index of the given string with the given char
	private String replace(String str, int index, char c) {
		StringBuilder sb = new StringBuilder(str);
		sb.setCharAt(index, c);
		return sb.toString();
	}


你可能感兴趣的:(Interview)