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

本文介绍了一种利用HashMap实现的双词匹配算法,该算法能够高效地从预定义的句子集合中找出同时包含两个指定关键词的句子。通过将句子分解为单词并存储在HashMap中,算法能快速检索出共同出现关键词的句子,适用于文本搜索和信息检索场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 stub
		Scanner 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.实验结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值