字梯

start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
从start开始每次变一个字母,从dict中寻找,最后到达end,输出路线

<pre name="code" class="java">package org.alg;

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

public class WordLadder {

public static void main(String[] args) {
		String start = "hit",end = "cog";
		Set<String> dict = new HashSet<String>();
		dict.add("hot");
		dict.add("dot");
		dict.add("dog");
		dict.add("log");
		wordLodder(start, end, dict);
	}

public static void wordLodder(String start, String end, Set<String> dict) {
		helper(start, end, dict);
	}

private static void helper(String start,String end,Set<String> dict) {
		//start变字符数组
		List<String> loading = new ArrayList<String>();
		loading.add(start);
		int len = dict.size();
		int i = 0;
		boolean success = false;
		while(i < start.length()) {
			char[] cs = start.toCharArray();
			boolean target = false;
			for(char c = 'a';c <= 'z';c++) {
				if(c == cs[i]) {
					continue;
				}
				cs[i] = c;
				String temp = new String(cs);
				if(dict.contains(temp)) {
					loading.add(temp);
					dict.remove(temp);
					start = temp;
					i = 0;
					target = true;
				}
				if(dict.size() == 0 && loading.size() == len + 1) {
					loading.add(end);
					System.out.println(loading.toString() + "长度:"+ loading.size());
					success = true;
				}
			}
			if(!target) {
				i++;
			}
		}
		if(!success) {
			System.out.println("不存在匹配的路线");
		}
	}
}


 
 

你可能感兴趣的:(字梯)