欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

一道Java面试题的做法

程序员文章站 2024-01-24 21:59:28
...
题目:给定一段产品的英文表述,包含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;
	}
}