本文共 1853 字,大约阅读时间需要 6 分钟。
先按单词长度分,然后按共性把,相同类别的存在一起,然后,把其中的一个作为key,其他参数就为value
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; public class WordMaps { public static Map<String, List<String>> computeAdjacentWords(List<String> words){ Map<String, List<String>> adjWords=new TreeMap<>(); Map<Integer,List<String>> wordsByLength=new TreeMap<>(); for(String w:words)//按长度存值 update(wordsByLength,w.length(),w); for(Map.Entry<Integer, List<String>> entry:wordsByLength.entrySet()){ List<String> groupsWords=entry.getValue();//指定长度的所有值 int groupNum=entry.getKey();//指定长度 for(int i=0;i<groupNum;i++){//在索引0到groupNum之间遍历 Map<String,List<String>> repToWord=new TreeMap<>(); for(String str:groupsWords){//对指定长度的所有值进行遍历 String rep=str.substring(0, i)+str.substring(i+1);//把该值删除其中的一位 update(repToWord,rep,str);//把当前的值,存到删除一位的key中 } for(List<String> wordClique:repToWord.values()){ if(wordClique.size()>=2){ for(String s1:wordClique){ for(String s2:wordClique){ if(s1!=s2){ update(adjWords,s1,s2); } } } } } } } return adjWords; } //跟新map 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); } } 测试: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=WordMaps.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://evjqi.baihongyu.com/