博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
TreeMap使用案例-多个映射(中级版)
阅读量:4228 次
发布时间:2019-05-26

本文共 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/

你可能感兴趣的文章
MySQL 表结构与键值
查看>>
MySQL存储引擎,表记录管理
查看>>
Mysql多表查询语句,授权用户与密码更改
查看>>
MySQL 备份与恢复
查看>>
采用IC传感器的相对湿度测量
查看>>
皮带传动实验
查看>>
微软的人才观
查看>>
Blizzard的MPQ文件格式搜索算法
查看>>
你的变量究竟存储在什么地方?
查看>>
s3c2410 中断异常处理(转)
查看>>
对张孝祥C语言试题其中一题的探讨 (转载)
查看>>
一些好的网站
查看>>
WinCE中的虚拟地址和实际的物理地址是如何对应
查看>>
Microsoft Windows CE 的内存使用
查看>>
makefile入门
查看>>
中科院计算所Goddon CPU诞生历史!牛!
查看>>
ispPAC
查看>>
为人处世小技巧
查看>>
结构体知识汇总
查看>>
内存操作越界略述
查看>>