常见算法 - 求给定字符串在字符串数组中转变成另一字符串的最少次数

Leetcode(127):

Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]

Output: 5

Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
思路与最少完全平方数和相同。构造图,可以改变某一字符到达就是一条路径。但这种解法超时了。。。

class Solution {
    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        	// 与最小完全平方数和思路一样,借助构造图,求最小路径
		Queue<String> queue = new LinkedList<String>();
		HashSet<String> set = new HashSet<String>();
		int level = 1;
		queue.offer(beginWord);
		while (!queue.isEmpty()) {
			int size = queue.size();
//			System.out.println(size);
			level++;
			for (int j = 0; j < size; j++) {
				String str = queue.poll();
				if (set.add(str)) {
					for (int i = 0; i < str.length(); i++) {
						char[] chars = str.toCharArray();
						for (char c = 'a'; c <= 'z'; c++) {
							chars[i] = c;			
							String word = new String(chars);
	                    	if (wordList.contains(word)) {
								if(word.equals(endWord)){
									return level;
								}else if(!set.contains(word)){
									queue.offer(word);
								}
							}
						}
					}
				}
			}
//			System.out.println("queueSize:"+queue.size());
		}
		return 0;
	}

}

猜你喜欢

转载自blog.csdn.net/b9x__/article/details/80229970