首页 > 其他分享 >TreeMap使用案例-多个映射(中级版)

TreeMap使用案例-多个映射(中级版)

时间:2022-12-12 16:35:09浏览次数:46  
标签:中级 String 映射 vine TreeMap mine words dine line

细节问题请看简单版
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]

标签:中级,String,映射,vine,TreeMap,mine,words,dine,line
From: https://blog.51cto.com/u_12026373/5930802

相关文章