欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

hashmap实现倒排索引——查询多个单词出现在多个句子中

发布时间:2024/9/30 37 豆豆
生活随笔 收集整理的这篇文章主要介绍了 hashmap实现倒排索引——查询多个单词出现在多个句子中 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

1.问题描述

给定三条句子:

d1=I like to watch the sun set with my friend.

d2=The Best Places to Watch The Sunset.

d3=My friend watches the sun come up.

输入两个单词,输出它的在哪些句子中出现过

 

2.利用hashmap<String,List<Integer>>来实现

import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Scanner;public class Main {public static HashMap<String, List> map=new HashMap<>();public static void way(String str,int word) {String str2="\\.";str=str.replaceAll("\\.", " .");String strs[]=str.split(" ");for (String string : strs) {string=string.toLowerCase();List<Integer> key=map.get(string);if (key==null) {key=new ArrayList<>();map.put(string, key);}if (!key.contains(string)) {key.add(word);}}}public static List<Integer> Intersect(List<Integer> p1,List<Integer> p2){int res=0;List<Integer> list=new ArrayList<>();int i=0;while (!p1.isEmpty()&&!p2.isEmpty()) {if (p1.get(i).equals(p2.get(i))) {list.add(p1.get(i));p1.remove(i);p2.remove(i);}else if(p1.get(i)<p2.get(i)){p1.remove(i);}else {p2.remove(i);}} return list;}public static void main(String[] args) {// TODO Auto-generated method stubScanner sc=new Scanner(System.in);String strs[]= {"I like to watch the sun set with my friend.","The Best Places to Watch The Sunset.","My friend watches the sun come up."};System.out.println("请输入多关键字:");String word=sc.next().toLowerCase();String word2=sc.next().toLowerCase();way(strs[0], 1);way(strs[1], 2);way(strs[2], 3);//System.out.println(map);//System.out.println(map.get(word));//System.out.println(map.get(word2));List<Integer> list=Intersect(map.get(word),map.get(word2));System.out.println(list);} }

3.实验结果

总结

以上是生活随笔为你收集整理的hashmap实现倒排索引——查询多个单词出现在多个句子中的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。