此题是某公司笔试最后一题,当时时间紧张没做出来,出来后也是思索了蛮久才弄出来,可是程序似乎太繁琐,算法没选好,毫无效率可言,废话少说,题目如下:
给定一段产品的英文描述,包含M个英文单词,每个单词以空格分隔,无其他标点,再给定N个英文单词关键字。请说明思路并编程实现方法 String extractSummary(String description,String [ ] Keywords):目标是找出此产品描述中包含N个关键词(每个关键词至少出现一次)的长度最短的子串,作为产品简介输出,编程语言不限。
package test;
import java.util.ArrayList;
import java.util.List;
public class FindMinSubString {
static String[] content = { "a", "c", "d", "a", "c", "b", "d", "e", "a",
"a", "b" };
static String[] key = { "b", "c", "d" };
static List<Integer> aaa = new ArrayList<Integer>();
static List<Integer> bbb = new ArrayList<Integer>();
static List<Integer> ccc = new ArrayList<Integer>();
static Integer []subInteger={0,0,0};
public static void main(String args[]) {
System.out.print("content为:");
printf(content);
System.out.print("\n" + " key为:");
printf(key);
findKey(content, key[0], aaa);
System.out.println("\n" + "关键字b在content中出现的位置 :" + aaa);
findKey(content, key[1], bbb);
System.out.println("关键字c在content中出现的位置 :" + bbb);
findKey(content, key[2], ccc);
System.out.println("关键字d在content中出现的位置 :" + ccc);
System.out.println("符合条件的最小子字符串长度为: "+findResult(aaa, bbb, ccc));
System.out.print("此子字符串为:");
for(int i=findMin(subInteger[0],subInteger[1],subInteger[2]);i<=findMax(subInteger[0],subInteger[1],subInteger[2]);i++){
System.out.print(content[i]+" ");
}
}
// 打印
static void printf(Object ary[]) {
for (int i = 0; i < ary.length; i++)
System.out.print(ary[i] + " ");
}
// 找关键字在全文的位置
static void findKey(String content[], String A, List<Integer> kkk) {
int i, j = 0;
for (i = 0; i < content.length; i++) {
if (content[i] == A) {
kkk.add(j, i);
j++;
}
}
}
// 找出三个数之间的最大差
static int findCha(int a, int b, int c) {
int max, min;
if (a > b)
max = a;
else
max = b;
if (max < c)
max = c;
if (a > b)
min = b;
else
min = a;
if (min > c)
min = c;
return max - min;
}
// 找出最小符合条件子字符串的长度
static int findResult(List<Integer> aaa, List<Integer> bbb,
List<Integer> ccc) {
int i, j, k,m;
int result = findCha(aaa.get(0), bbb.get(0), ccc.get(0));
subInteger[0]=aaa.get(0);
subInteger[1]=bbb.get(0);
subInteger[2]=ccc.get(0);
for (i = 0; i < aaa.size(); i++)
for (j = 0; j < bbb.size(); j++)
for (k = 0; k < ccc.size(); k++) {
if (result > findCha(aaa.get(i), bbb.get(j), ccc.get(k))){
result = findCha(aaa.get(i), bbb.get(j), ccc.get(k));
subInteger[0]=aaa.get(i);
subInteger[1]=bbb.get(j);
subInteger[2]=ccc.get(k);
}
}
return result + 1;
}
//找三个数中的最大值
static int findMax(int a,int b,int c){
int max;
if(a>b)max=a;
else max=b;
if(max<c)max=c;
return max;
}
//找三个数中的最小值
static int findMin(int a,int b,int c){
int min;
if(a<b)min=a;
else min=b;
if(min>c)min=c;
return min;
}
}
输出结果:
content为:a c d a c b d e a a b
key为:b c d
关键字b在content中出现的位置 :[5, 10]
关键字c在content中出现的位置 :[1, 4]
关键字d在content中出现的位置 :[2, 6]
符合条件的最小子字符串长度为: 3
此子字符串为:c b d