您的位置:首页 > 其它

二分法找字符串

2018-02-04 16:40 120 查看
题目描述

有一个排过序的字符串数组,但是其中有插入了一些空字符串,请设计一个算法,找出给定字符串的位置。算法的查找部分的复杂度应该为log级别。

给定一个string数组str,同时给定数组大小n和需要查找的string x,请返回该串的位置(位置从零开始)。

测试样例:

[“a”,”b”,”“,”c”,”“,”d”],6,”c”

返回:3

class Finder {
public:
int findString(vector<string> str, int n, string x) {
// write code here
int start = 0, end = n - 1;
int count=0;
while (start<end){
int mid = (start + end) / 2;
if (str[mid] == ""){
while (mid > start && str[mid] == ""){
mid--;
}
while (mid<end&&str[mid] == ""){
mid++;
}

}
if (str[mid]>x){
end = mid - 1;
}
else if (str[mid]<x){
start = mid + 1;
}
else if (str[mid] == x){
return mid;
}
}
return start;
}
};


class Finder {
public:
int findString(vector<string> str, int n, string x) {
// write code here
int i = 0;
int j = n - 1;
while (i <= j)
{
int mid = (i + j) / 2;
if (str[mid] == " ")
{
int index = mid;
while (index>=i&&str[mid] == " ")
{
--index;
}
if (str[index] == x) return index;
else if (str[index] > x)
j = index - 1;
else
i = index + 1;
}
else
{
if (str[mid] == x)
return mid;
else if (str[mid] > x)
j = mid - 1;
else
i = mid + 1;
}

}
return -1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: