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