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

细节问题请看简单版

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]

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值