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