Skip to content

Instantly share code, notes, and snippets.

@zachelko
Last active June 27, 2016 08:10
Show Gist options
  • Save zachelko/9177987 to your computer and use it in GitHub Desktop.
Save zachelko/9177987 to your computer and use it in GitHub Desktop.
Find the number of times the most-common substring occurs in a given string
/* Given an input string of size n, return the number of occurrences
* of the most common substring between lengths k,l.
*/
int findOccurrencesOfMostCommonSubstring(int n, int k, int l, const string &input)
{
std::map<std::string, int> substringMap;
int maxOccurrences = 1;
// 1. Build every legal substring with lengths between k and l
// 2. Place into map
// 3. Increment count associated with the substring
// 4. Determine if it is most common
// 5. Return count for most common
const int inputLen = input.size();
// i serves as our left-bound for the substrings
for (int i = 0; i < inputLen - 1; ++i) {
// j serves as our right-bound for the substrings
// 1. At each right-bound, create the longest legal substring that we can without
// walking past the end of the string.
// 2. Insert it into the map.
// 3. Update maxOccurrences
// 4. When we're finished, return maxOccurrences.
for (int j = k; j <= l && i + j <= inputLen; ++j) {
const std::string current = input.substr(i,j);
// DEBUG
// std::cout << "("<< i << "," << j << ") : " << current << std::endl;
// If 'current' isn't in the map, it will insert a value
// of 0. This means we can simply increment currentValue
// regardless of it being present in the map or not,
// and we'll achieve correct behavior in both cases.
int &currentValue = substringMap[current];
maxOccurrences =
(++currentValue > maxOccurrences)
? currentValue : maxOccurrences;
}
}
return maxOccurrences;
}
@rootChuTney-RaviBhanot
Copy link

@zachelko - Line 25 should be
for (int j = k; j <= l && j <= inputLen; ++j) {

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment