2007百度校园招聘笔试题 问题:
http://www.ad0.cn/netfetch/read.php/1132.htm
http://www.ad0.cn/netfetch/read.php/1133.htm
题目一:
一个文本文件有多行,每行为一个URL。请编写代码,统计出URL中的文件名及出现次数
a) 文件名不包括域名、路径和URL参数,例如http://www.ourday.cn/bbs/forumdisplay.php?fid=18中的文件名是forumdisplay。
b) 部分URL可能没有文件名,例如http://www.ourday.cn/,这类统计为“空文件名”。
c) 出现在不同URL中的相同文件名视为同一文件名,例如http://www.ourday.cn/index.php和ftp://ftp.ourday.cn/index.php为同一文件名
文件内容示例如下:
http://www.ourday.cn/bbs/redirect.php?tid=480&goto=lastpost#lastpost
http://www.ourday.cn/index.php
ftp://ftp.ourday.cn/index.php
http://www.ourday.cn/bbs/index.php?k=8
http://www.ourday.cn/bbs/forumdisplay.php?fid=16
http://www.ourday.cn/bbs/viewthread.php?tid=444&extra=page%3D1
http://www.ourday.cn/
http://www.ourday.com.cn/
以上url地址经修改,不影响试题内容。
Answer1:
第一题
简评
百度的主要业务是搜索,搜索的基本原理如下
1.编写爬虫程序到互联网上抓取网页海量的网页。
2.将抓取来的网页通过抽取,以一定的格式保存在能快速检索的文件系统中。
3.把用户输入的字符串进行拆分成关键字去文件系统中查询并返回结果。
由以上3点可见,字符串的分析,抽取在搜索引擎中的地位是何等重要。
因此,百度的笔试面试题中,出现这样的题就变得理所当然了。
以下是该题的java实现,代码如下:
import java.net.*;
import java.io.*;
import java.util.*;
/** * @author tzy * 在j2sdk1.4.2下测试通过 */
public class FileNameStat{
private String srcPath;//要统计的文件路径
private Map statMap;//用于统计的map
public FileNameStat(String srcPath)
{
this.srcPath=srcPath;
statMap=new TreeMap();
}
/*获得要统计的URL的文件名*/
public String getFileName(String urlString)
{
URL url=null;
String filePath=null;
String fileName=null;
try
{
url=new URL(urlString);
filePath=url.getPath();
int index=0;
if ((index=filePath.lastIndexOf(/"//"))!=-1)
{
fileName=filePath.substring(index+1);
}
else
{
fileName=/"/";
}
}
catch(MalformedURLException e)
{
}
return fileName;
}
/*统计指定文件名的个数*/
public void stat(String filename)
{
Integer count=null;
if(statMap.get(filename)!=null)
{
count=(Integer)statMap.get(filename);
count=new Integer(count.intValue()+1);
}
else
{
count=new Integer(1);
}
statMap.put(filename,count);
}
/*统计的主方法*/
public void start() throws FileNotFoundException,IOException
{
BufferedReader bfin=new BufferedReader(new FileReader(this.srcPath));
String temp=null;
while((temp=bfin.readLine())!=null)
{
stat(getFileName(temp));
}
}
/*输出统计结果*/
public void result()
{
Iterator it=statMap.entrySet().iterator();
while(it.hasNext())
{
Map.Entry entry=(Map.Entry)(it.next());
System.out.println((entry.getKey().equals(/"/")?/"空文件名/":entry.getKey()) + /"的个数是/" + entry.getValue());
}
}
public static void main(String[] args) throws Exception
{
FileNameStat fns=new FileNameStat(/"src.txt/");//指定成待统计文件
fns.start();
fns.result();
}
}