Possible Duplicate:
What is the complexity of std::string::substr member function?
I am attempting a naive solution to the common substring problem. I do this by first finding all the substrings of the first string and adding them to a hash set. Then, I find the substrings of the second string and see if they exist in the hash set, and adjust the longest substring if the length is greater than the current max substring. What I was wondering is: what is the runtime of substr, in terms of the length of the str1 (let’s say str1 has length n)?
#include<hash_set>
string longestCommonSubstring(string str1, string str2) {
hash_set<string> substrings;
string maxSubstring = "";
int maxLength = 0;
for (int i = 0; i < str1.size(); i++) {
for (int j = i+1; j < str1.size(); j++) {
substrings.insert(str1.substr(i,j-i));
}
}
for (int i = 0; i < str2.size(); i++) {
for (int j = i+1; j < str2.size(); j++) {
if (substrings.find(str2.substr(i,j-i)) != substrings.end()) {
if (j-i > maxLength) {
maxSubstring = str2.substr(i,j-1);
maxLength = j - i;
}
}
}
}
}
There isn’t a specified complexity for
substr, butstringhas constant-time random access, andsubstrmakes a new string of the given length, so it’ll be essentially the cost of copying that many characters.Note that GCC implements
std::stringwith reference counting (illegally so), so the actual cost of making a copy may vary depending on your implementation.