import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;public class SerachBase {//存储搜索域,index为每个字的char值private static HashSet[] searchid = new HashSet[100000]; //存储搜索域中的词汇在搜索文字中出现的次数private HashMap<String, Integer> searchtimes;//存储搜索结果的javabean,times存储含有搜索文字的次数,依次排序进行显示class searchbean implements Comparable<searchbean>{private String word;private int times;public String getWord() {return word;}public void setWord(String word) {this.word = word;}public int getTimes() {return times;}public void setTimes(int times) {this.times = times;}@Overridepublic int compareTo(searchbean o) {if (this.times<o.times){return -1;}else if(this.times>o.times){return 1;}else{return 0;}}} //搜索public List<searchbean> search(String word) {searchtimes=new HashMap<String, Integer>();//记录含有word中文字的词语HashSet<String> haveword=new HashSet<String>();for(int i=0;i<word.length();i++){int where = word.charAt(i);int time=0;if(searchid[where]==null){continue;}HashSet<String> a=searchid[where];for(String s1:a){if(s1.indexOf(word.substring(i, i+1))!=-1){time+=1;searchtimes.put(s1, time);haveword.add(s1);}}}List<searchbean> l1=new ArrayList<SerachBase.searchbean>();for(String s2:haveword){searchbean s1=new searchbean();s1.setWord(s2);s1.setTimes(searchtimes.get(s2));l1.add(s1);}//排序Collections.sort(l1);return l1;}//将String存入到搜索域public void addsearchword(String word){for(int i=0;i<word.length();i++){int where=word.charAt(i);HashSet<String> a=searchid[where];if(a==null){ a=new HashSet<String>(); a.add(word);searchid[where]=a;}else{ a.add(word);searchid[where]=a;}}}public static void main(String[] args) {SerachBase s1=new SerachBase();s1.addsearchword("萨达");s1.addsearchword("拉萨");s1.addsearchword("达姆");List<searchbean> l1=s1.search("拉萨");for(searchbean s:l1){System.out.println(s.getWord());}}}
详细解决方案
简单的文字搜索功能
热度:49 发布时间:2023-10-28 01:04:48.0
相关解决方案