Hard 单词变型成另一个单词 @CareerCup
BFS的变形体。对起始单词的每一个字母都做替换,把替换后的单词加入到queue中,并同时维护一个Map来记录变化前单词和变化后单词的联系。用来回溯时能打印出路径。
package Hard;import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;/**
* Given two words of equal length that are in a dictionary, write a method to trans-
form one word into another word by changing only one letter at a time. The new
word you get in each step must be in the dictionary.给定两个有着相同长度且都在字典内的单词,要求写一个方法来把一个单词变型成另一个单词。
一次只能转换一个字母,且每次生成的单词必须在字典内
*
*/
public class S18_10 {public static LinkedList transform(String startWord, String stopWord, Set dictionary) {
startWord = startWord.toUpperCase();
stopWord = stopWord.toUpperCase();
Queue actionQueue = new LinkedList();
Set visitedSet = new HashSet();
Map backtrackMap = new TreeMap();actionQueue.add(startWord);
visitedSet.add(startWord);while (!actionQueue.isEmpty()) {
String w = actionQueue.poll();
// For each possible word v from w with one edit operation
for (String v : getOneEditWords(w)) {
if (v.equals(stopWord)) { // Found our word! Now, back track.
LinkedList list = new LinkedList();
list.add(v); // Append v to list
while (w != null) {
list.add(0, w);
w = backtrackMap.get(w);
}
return list;
}// If v is a dictionary word
if (dictionary.contains(v)) {
if (!visitedSet.contains(v)) {
actionQueue.add(v);
visitedSet.add(v); // mark visited
backtrackMap.put(v, w); // w is the previous state of v
}
}
}
}
return null;
}// 改变word的某一个字母
private static Set getOneEditWords(String word) {
Set words = new TreeSet();for (int i = 0; i < word.length(); i++) { // for every letter
char[] wordArray = word.toCharArray();
// change that letter to something else
for (char c = 'A'; c <= 'Z'; c++) {
if (c != word.charAt(i)) {
wordArray[i] = c;
words.add(new String(wordArray));
}
}
}
return words;
}public static HashSet setupDictionary(String[] words) {
HashSet hash = new HashSet();
for (String word : words) {
hash.add(word.toUpperCase());
}
return hash;
}public static void main(String[] args) {
String[] words = { "maps", "tan", "tree", "apple", "cans", "help",
"aped", "free", "apes", "flat", "trap", "fret", "trip", "trie",
"frat", "fril" };
HashSet dict = setupDictionary(words);
LinkedList list = transform("tree", "flat", dict);
for (String word : list) {
System.out.println(word);
}
}
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
