【LeetCode】Word Ladder

Word Ladder
Total Accepted: 9317 Total Submissions: 53652 My Submissions

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.
【解题思路】
BFS求解最短路径。

Java AC

public class Solution {
    public int ladderLength(String start, String end,HashSet<String> dict) {
		if (dict == null || dict.isEmpty()) {
			return 0;
		}
		Queue<Node> strQueue = new LinkedList<Node>();
		HashSet<String> visitedSet = new HashSet<String>();
		strQueue.add(new Node(start, 1));
		visitedSet.add(start);
		int wordLen = start.length();
		while (!strQueue.isEmpty()) {
			Node node = strQueue.peek();
			strQueue.poll();
			for (int i = 0; i < wordLen; i++) {
			    StringBuffer sb = new StringBuffer(node.word);
				for (char j = 'a'; j <= 'z'; j++) {
					sb.setCharAt(i, j);
					String tempWord = sb.toString();
					if (tempWord.equals(end)) {
						return node.len+1;
					}else {
						if (dict.contains(tempWord) && !visitedSet.contains(tempWord)) {
							strQueue.add(new Node(tempWord, node.len+1));
							visitedSet.add(tempWord);
						}
					}
				}
			}
		}
		return 0;
	}
	private static class Node{
		String word;
		int len;
		public Node(String word, int len) {
			super();
			this.word = word;
			this.len = len;
		}
	}
}


你可能感兴趣的:(【LeetCode】Word Ladder)