Dec 19, 2008

having a string say, "foobarfoo", in which "fo" and "oo" are repeated twice. You have to find all such repeated pairs whose length is tow in O(n) time

having a string say, "foobarfoo", in which "fo" and "oo" are repeated twice. You have to find all such repeated pairs whose length is tow in O(n) time. The string can only have alphanumeric elements in it and code it in C.

Use suffix tree O(n) which is not easy to code
Use dp which is O(n^2)
Use hash table, it can be done in O(n).
Traverse the string, each time take two consecutive characters, hash them in the hashtable, the hash function is just base 36 number system

void foo(char* str)
{
int i=0;
int j=1;
int hashtable[1296]={0};//36*36
while(str[j])
{
int idx=(str[i]-'a')*36+(str[j]-'a');//base 36
if(!hashtable[idx])
hashtable[idx]=1;
else cout<<str[i]<<str[j]<<endl;
i++;
j++;
}
}

No comments:

Post a Comment