您的位置:首页 > 职场人生

百度面试题及我的解答(2)

2009-11-25 23:20 253 查看
接下来开始介绍主程序流程:

使用了GetTickCount()函数测量每一部分代码的运行时间。

第一步为读取数据,并加入Hash表。

//打开字典文件
ifstream srctxt;
char buf[256]={0};
buf[255]=0;
srctxt.open("dict.txt");
if (!srctxt.is_open())
{
cerr<< "open file dict.txt fail!"<<endl;
return -1;
}

//初始化Hash表,桶设置的很大,不需要再用质数去模运算。
HashMethod1 *pHashMethod = new HashMethod1;
if ( !pHashMethod->InitHashTbl(65535) ) { return -1;}
//字典文件每行一个单词,读取单词并加入Hash表
while (!srctxt.eof())
{
srctxt.getline(buf, 255);;
if ( 0 != buf[255] ){
cerr << "buf overflow!" <<endl;
buf[255]=0;
cerr << buf << endl;
return -2;
}

if ( !pHashMethod->Add(buf) ) { return -1;}

}
srctxt.close();
tickCount1 = GetTickCount();

cerr << tickCount1- tickCount0 << endl;


第二步就是遍历Hash表。读取每一个冲突链表,并比较其中的所有字符串,得到变位词表。

//遍历Hash表,输出变位词。
tickCount0 = GetTickCount();
ofstream result("result.txt");
pHashMethod->TraverseTbl(&Step4TrverseProcess,result);
result.close();
tickCount1 = GetTickCount();
cerr << tickCount1- tickCount0 << endl;


具体的遍历流程实现在Stepp4TrverseProcess函数中,这个函数的代码最后给出吧。

下一回给出类的定义。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: