一道Java面试题的做法

题目:给定一段产品的英文表述,包含M个英文单词,每个英文单词以空格分隔,无其他标志符号;再给定N个英文关键字,请说明思路并编程实现String extractSummary(Stringdescription,String[] keyword):目标是找出产品描述中包含N个关键字(每个关键字至少出现一次)的长度最短的子串。

实现的代码如下:

package date0621;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

/**
*@author TonyJ
*@time 2011-6-21 上午08:44:26
*/
public class Test01 {
public static void main(String[] args) {
String src = "Provides Providesddd Providesthe Providesclasses "
+ "Provids necessary to create an applet and the classes an "
+ "applet uses to communicate with its applet context";
String key[] = { "Pr", "vi", "o" };
System.out.println(extractSummary(src, key));
}

// 给定一段产品的英文表述,包含M个英文单词,每个英文单词以空格分隔,无其他标志符号;
// 再给定N个英文关键字,请说明思路并编程实现String extractSummary(String
// description,String[] keyword):
// 目标是找出产品描述中包含N个关键字(每个关键字至少出现一次)的长度最短的子串
public static String extractSummary(String description, String[] keyword) {
String[] str = description.split(" ");
Map map = new HashMap();//用键值对的方式存储,键是字符串的值,值是字符串的长度
boolean isContain = true;
for (int i = 0; i < str.length; i++) {
for (int j = 0; j < keyword.length; j++) {
if (!str[i].contains(keyword[j])) {
isContain = false;
break;
}
}
if (isContain) {
map.put(str[i], str[i].length() + "");
}
}
String res = "";
Iterator iter = map.entrySet().iterator();
Iterator iter2 = map.entrySet().iterator();
int temp = Integer.parseInt(((Entry) iter2.next()).getValue() + "");
while (iter.hasNext()) {//迭代判断哪个是字符串的长度最短
Map.Entry entry = (Entry) iter.next();
//这是jdk1.4的环境下做的 不支持类型的自动装箱和拆箱
if (Integer.parseInt(entry.getValue() + "") <=temp) {
temp = Integer.parseInt(entry.getValue() + "");
res = (String) entry.getKey();
}
}

return res;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值