本文共 1817 字,大约阅读时间需要 6 分钟。
细节问题请看简单版
public class WordMapn {
public static Map<String, List<String>> computeAdjacentWords(List<String> theWords){ Map<String, List<String>> adjWords=new TreeMap<>(); //只要长度相等的单词才有可能满足条件,先按长度找出来,存在wordsByLength中 Map<Integer,List<String>> wordsByLength=new TreeMap<>(); for(String w:theWords){ update(wordsByLength,w.length(),w); } //对于每种长度的单词,只要进行内部查找就可以了 for(List<String> groupsWords:wordsByLength.values()){ String[] words=new String[groupsWords.size()]; groupsWords.toArray(words); for(int i=0;i<words.length;i++){ for(int j=i+1;j<words.length;j++){ if(oneCharOff(words[i],words[j])){ update(adjWords,words[i],words[j]); update(adjWords,words[j],words[i]); } } } } return adjWords; } private static <KeyType> void update(Map<KeyType, List<String>> m, KeyType key,String value){ List<String> lst=m.get(key); if(lst==null){ lst=new ArrayList<>(); m.put(key, lst); } lst.add(value); } //检测两个单词时候只在一个字母上不同 private static boolean oneCharOff(String word1,String word2){ if(word1.length()!=word2.length()){ return false; } int diffs=0; for(int i=0;i<word1.length();i++){ if(word1.charAt(i)!=word2.charAt(i)){ if(++diffs>1){ return false; } } } return diffs==1; } }测试:
public static void main(String[] args) { // TODO Auto-generated method stub List<String> list=null; String[] a=new String[]{"dine","line","mine","pine","vine","wide","wife","wipe","wire"}; list=Arrays.asList(a); Map<String,List<String>> m=WordMapn.computeAdjacentWords(list); for(Map.Entry<String,List<String>> me : m.entrySet()) { System.out.println(me.getKey() + ": " + me.getValue()); }效果:
dine: [line, mine, pine, vine]
line: [dine, mine, pine, vine] mine: [dine, line, pine, vine] pine: [dine, line, mine, vine] vine: [dine, line, mine, pine] wide: [wife, wipe, wire] wife: [wide, wipe, wire] wipe: [wide, wife, wire] wire: [wide, wife, wipe]转载地址:http://hvjqi.baihongyu.com/