【题目】
有个顺序排好的字符串数组,其中随机的插入一些空串,指定一字符串,求其对应的下标。
【解析】
既然是顺序排好要求查找,就可以使用分治法。字符串的比较使用strcmp()strcmp()strcmp()函数,此题主要考察的是对空串的处理:遇到空串,则将midmidmid下标向左或向右挪到非空串,再进行判断。
另外,注意判断查找不到一个串的情况,也就是说它的索引超出了范围仍未找到。
【代码】
#include<iostream>
#include<cstring>
using namespace std;
const char ff[] = "ef";
int main()
{
char str[7][3] = { "ab","","bc","cd","","","ef" };
int left = 0, right = 6;
while (left <= right)
{
int mid = (left + right) >> 1;
while (!strcmp(str[mid], "")) {
mid++;
if (mid > right)
return 0;
}
if (strcmp(str[mid], ff) < 0)
left = mid + 1;
else if (strcmp(str[mid], ff) > 0)
right = mid - 1;
else {
cout << mid << endl;
break;
}
}
return 0;
}