Given set of words, find an area of the text where these words are close

#include <iostream>
#include <list>
#include <string>
#include <algorithm>

using namespace std;

struct Word {
string word;
const char *pos;

bool operator == (const string & str) {
return word == str;
}

Word(const string &w, const char *p) : word(w), pos(p){}

};

typedef list<Word> Window;
typedef list<string> Words;

string textarea(const Words &words, const char *str) {

string result;

if(!str || !*str) return result;

const char *p = str;

Window window;
string word;

while(1) {

if(*p == ' ' || *p == '') { //end of word

word = string(str, p - str);

//find the word in words
if(find(words.begin(), words.end(), word) != words.end()) {

//find the word in window
Window::iterator wit = find(window.begin(), window.end(), word);

//if word is there, reduce the window till the next word in window
if(wit != window.end()) {
window.erase(window.begin(), ++wit);
}

//place the current word in window
window.push_back(Word(word, str));

//if the size of the window is same as size of words
if(window.size() == words.size()) {

//starting of the window is the pos of the first word
const char* start = window.front().pos;

string temp(start, p - start);

if( result.empty() || result.size() > temp.size() )
result = temp;
}
}
str = p + 1;
}
if(*p == '') break;
p++;

};

return result;
}


int main() {

Words l;

l.push_back("bat");
l.push_back("cat");
l.push_back("mat");

cout<<textarea(l, "bat stop the mat blah blah cat by mat bat ss cat t mat bat")<<endl;
return 0;
}
Advertisements

One thought on “Given set of words, find an area of the text where these words are close

  1. This is a good blog. But apart from writing the program it would be tremendously useful if you can mention the exact algo you have taken along with complexity. After this it becomes to write a program…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s