hashmap实现倒排索引——查询多个单词出现在多个句子中
生活随笔
收集整理的這篇文章主要介紹了
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实现倒排索引——查询多个单词出现在多个句子中的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JavaWeb学习之路——SSM框架之S
- 下一篇: 后台开发人员面试内容——操作系统(一)