#include <iostream>
#include <vector>
#include <string>
#include <time.h>
using namespace std;
int find_right_str(vector<string> &v, int pos)
{
vector<string>::const_iterator it;
int idx = 0;
for(it = v.begin(); it != v.end(); ++it){
if(idx >= pos && !((*it).empty())){
return idx;
}
idx ++;
}
return -1;
}
int find_left_str(vector<string> &v, int pos)
{
vector<string>::const_reverse_iterator it;
int idx = v.size() - 1;
for(it = v.rbegin();it != v.rend(); ++it){
if(idx <= pos && (!(*it).empty())){
return idx;
}
idx --;
}
return -1;
}
void add_spaces(vector<string> &v)
{
int n = rand() % 5;
for(int i = 0; i < n; i++){
v.push_back("");
}
}
void print_list(vector<string> &v)
{
vector<string>::const_iterator it;
for(it = v.begin(); it != v.end(); ++it){
if((*it).empty()){
cout << "\"\"" << ",";
}
else{
cout << "\"" << (*it) << "\"" << ",";
}
}
cout << endl;
}
int find_str(vector<string> &v, string s)
{
int low = 0;
int up = v.size() - 1;
low = find_right_str(v, low);
up = find_left_str(v, up);
if(low == -1 && up == -1){ // no none-empty strings
return -1;
}
while(low <= up){
int m, mr, ml;
m = (low + up) / 2;
mr = find_right_str(v, m);
ml = find_left_str(v, m);
low = find_left_str(v, low);
up = find_right_str(v, up);
if( find_right_str(v, low + 1) == up || find_left_str(v, up -1) == low){ // avoid no string between low and up
if(v.at(low) == s){
return low;
}
else if(v.at(up) == s){
return up;
}
else{
return -1;
}
}
if(v.at(ml) == s){
return ml;
}
else if(v.at(mr) == s){
return mr;
}
else if(v.at(ml) > s){
up = ml - 1;
}
else if(v.at(mr) < s){
low = mr + 1;
}
}
return -1;
}
int main(int argc, char* argv[])
{
srand((unsigned)time(NULL));
string slist[] = {"a", "christmas", "church", "eve", "good", "government", "merry", "old", "senior"};
int n = sizeof(slist)/sizeof(string);
cout << "total elements: " << n << endl;
vector<string> v;
v.push_back("");
for(int i = 0; i < n; i++){
v.push_back(slist[i]);
add_spaces(v);
}
cout << "The string list is: " << endl;
print_list(v);
string findstr[5] = {"a", "zoo", "church", "prince", "senior"};
for(int i = 0; i < 5; i++){
cout << "find " << findstr[i] << " at: " << find_str(v, findstr[i]) << endl;
}
return 0;
}
Output
total elements: 9
The string list is:
"","a","christmas","","","","","church","","","","","eve","","good","","","government","","","","","merry","old","","sen
ior","","","","",
find a at: 1
find zoo at: -1
find church at: 7
find prince at: -1
find senior at: 25
Solution
Problem
Given a sorted array of strings which is interspersed with empty strings, write a method to find the location of a given string.
Example: find “ball” in [“at”, “”, “”, “”, “ball”, “”, “”, “car”, “”, “”, “dad”, “”, “”] will return 4
Example: find “ballcar” in [“at”, “”, “”, “”, “”, “ball”, “car”, “”, “”, “dad”, “”, “”] will return -1