Alibaba笔试题:获取产品简介

来源:互联网 发布:java项目导出war包 编辑:程序博客网 时间:2024/05/29 15:08
Alibaba笔试题:给定一段产品的英文描述,包含M个英文字母,每个英文单词以空格分隔,无其他标点符号;再给定N个英文单词关键字,请说明思路并编程实现方法
    String extractSummary(String description,String[] key words)

目标是找出此产品描述中包含N个关键字(每个关键词至少出现一次)的长度最短的子串,作为产品简介输出。


import java.util.HashMap;
import java.util.Map;


public class ShortSummary {


static int count[];
static Map<String,Integer> map = new HashMap<String,Integer>();
static String[] text;

public static void main(String[] args) {
text = "When we are born we are unblemished As we grow we develop many complexities due to many influences in our lives".split(" ");  
   String[] keywords = {"develop","complexities"};  
   extractSummary(text,keywords);
}

public static void extractSummary(String[] description,String[] keywords) {
count = new int[keywords.length];
for(int i=0;i<keywords.length;i++){
map.put(keywords[i], i);
}
int start = 0; int len = description.length; int min=len;
for(int i=0;i<len;i++){
int t=getLocation(i,len-1);
if (t>-1) {
if (min>t) {
min = t;
start=i;
}
}
}
for(int i=start;i<=start+min;i++) {
System.out.print(description[i]+" ");
}
}

public static int getLocation(int from,int to){
int start = from;
while( from <= to&&!isAllGetted()) {
Integer i = map.get(text[from]);
if (i!=null) {
count[i]++;
}
from++;
}
if (isAllGetted())  
       return from - start - 1;  
return -1;
}

public static boolean isAllGetted() {
for(int i=0;i<count.length;i++){
if (count[i]==0) {
return false;
}
}
return true;
}
}

0 0
原创粉丝点击