Hard 单词变型成另一个单词 @CareerCup


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<String> transform(String startWord, String stopWord, Set<String> dictionary) {
startWord = startWord.toUpperCase();
stopWord = stopWord.toUpperCase();
Queue<String> actionQueue = new LinkedList<String>();
Set<String> visitedSet = new HashSet<String>();
Map<String, String> backtrackMap = new TreeMap<String, String>();


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<String> list = new LinkedList<String>();
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<String> getOneEditWords(String word) {
Set<String> words = new TreeSet<String>();

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<String> setupDictionary(String[] words) {
HashSet<String> hash = new HashSet<String>();
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<String> dict = setupDictionary(words);
LinkedList<String> list = transform("tree", "flat", dict);
for (String word : list) {
System.out.println(word);
}
}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值