[leetcode]127. Word Ladder@Java解题报告

https://leetcode.com/problems/word-ladder/#/description



Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence frombeginWord to endWord, such that:

  1. Only one letter can be changed at a time.
  2. Each transformed word must exist in the word list. Note that beginWord is not a transformed word.

For example,

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

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.
  • You may assume no duplicates in the word list.
  • You may assume beginWord and endWord are non-empty and are not the same.

UPDATE (2017/1/20):
The wordList parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

这道题做起来很崩溃,leetcode最近又改了test cases,导致很多推荐解答也TLE,下面两种方法虽然在leetcode超时,在牛客网是可以通过的。面试中这两种解法面试官应该是认可的吧。


说下思路:利用图BFS搜索

我们先给题目进行图的映射,顶点则是每个字符串,然后两个字符串如果相差一个字符则我们进行连边。接下来看看这个方法的优势,注意到我们的字符集只有小写字母,而且字符串长度固定,假设是L。那么可以注意到每一个字符可以对应的边则有25个(26个小写字母减去自己),那么一个字符串可能存在的边是25*L条。接下来就是检测这些边对应的字符串是否在字典里,就可以得到一个完整的图的结构了。根据题目的要求,等价于求这个图一个顶点到另一个顶点的最短路径,一般我们用广度优先搜索(不熟悉搜索的朋友可以看看Clone Graph)即可。这个算法中最坏情况是把所有长度为L的字符串都看一下,或者把字典中的字符串都看一下,而长度为L的字符串总共有26^L,所以时间复杂度是O(min(26^L, size(dict))


package go.jacob.day727;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.junit.Test;

/**
 * 127. Word Ladder
 * 
 * @author Jacob
 *
 */
public class Demo1 {
	@Test
	public void testName() throws Exception {
		String beginWord="hit";
		String endWord="cog";
		List<String> wordList=new ArrayList<String>();
		wordList.add("hot");
		wordList.add("dot");
		wordList.add("dog");
		wordList.add("lot");
		wordList.add("log");
		wordList.add("cog");
		System.out.println(ladderLength(beginWord,endWord,wordList));
		//"hot","dot","dog","lot","log","cog"
	}
	/*
	 * 双结尾的图BFS解法:理论上要比用map的快
	 */
	public int ladderLength(String beginWord, String endWord, List<String> wordList) {
		if (!wordList.contains(endWord)){
			//System.out.println("开始");
			return 0;
		}
		// 分别存放beginWord和endWord的BFS元素
		Set<String> beginSet = new HashSet<String>();
		Set<String> endSet = new HashSet<String>();
		Set<String> visited = new HashSet<String>();
		int len = 1;
		beginSet.add(beginWord);
		endSet.add(endWord);

		while (!beginSet.isEmpty() && !endSet.isEmpty()) {
			// 保证beginSet的元素最少,这样BFS遍历的节点减少,能够缩短运行时间
			if (beginSet.size() > endSet.size()) {
				Set<String> tmpSet = beginSet;
				beginSet = endSet;
				endSet = tmpSet;
			}
			Set<String> temp = new HashSet<String>();
			for (String s : beginSet) {
				//为了调用StringBuilder的setCharAt方法
				for (int i = 0; i < s.length(); i++) {
					StringBuilder sb = new StringBuilder(s);
					for (char j = 'a'; j <= 'z'; j++) {
						sb.setCharAt(i, j);
						if (endSet.contains(sb.toString())){
							return len + 1;
						}
						if (!visited.contains(sb.toString()) && wordList.contains(sb.toString())) {
							visited.add(sb.toString());
							temp.add(sb.toString());
						}
					}
				}
			}
			len++;
			beginSet = temp;
		}
		return 0;
	}
	
	public static void main(String[] args) {
		String s="1234";
		StringBuilder sb=new StringBuilder(s);
		sb.setCharAt(1, 'b');
		System.out.println(sb.toString());
	}
}


package go.jacob.day726;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;

/**
 * 127. Word Ladder
 * 
 * @author Jacob 图BFS的应用 
 * 这道题做的有点崩溃,各种超时
 */
public class Demo3 {
	
	
	
	public int ladderLength(String start, String end, List<String> dict) {
		if(!dict.contains(end))
			return 0;
		// Use queue to help BFS
		Queue<String> queue = new LinkedList<String>();
		queue.add(start);
		queue.add(null);

		// Mark visited word
		Set<String> visited = new HashSet<String>();
		visited.add(start);

		int level = 1;

		while (!queue.isEmpty()) {
			String str = queue.poll();

			if (str != null) {
				// Modify str's each character (so word distance is 1)
				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);

						// Found the end word
						if (word.equals(end))
							return level + 1;

						// Put it to the queue
						if (dict.contains(word) && !visited.contains(word)) {
							queue.add(word);
							visited.add(word);
						}
					}
				}
			} else {
				level++;

				if (!queue.isEmpty()) {
					queue.add(null);
				}
			}
		}
		return 0;
	}

	/*
	 * 
	 */
	public int ladderLength_1(String beginWord, String endWord, List<String> wordList) {
		if(!wordList.contains(endWord))
			return 0;
	    Queue<String> queue = new LinkedList<String>();
	    queue.add(beginWord);
	    int level = 0;
	    while(!queue.isEmpty()){
	        int size = queue.size();
	        for(int i = 0; i < size; i++){
	            String cur = queue.remove();
	            if(cur.equals(endWord)){ return level + 1;}
	            for(int j = 0; j < cur.length(); j++){
	                char[] word = cur.toCharArray();
	                for(char ch = 'a'; ch < 'z'; ch++){
	                    word[j] = ch;
	                    String check = new String(word);
	                    if(!check.equals(cur) && wordList.contains(check)){
	                        queue.add(check);
	                        wordList.remove(check);
	                    }
	                }
	            }
	        }
	        level++;
	    }
	    return 0;
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值