Skip to content

Instantly share code, notes, and snippets.

@eclipselu
Created September 9, 2016 09:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eclipselu/da7b4670d6b9ddd6787124ed9ba94d97 to your computer and use it in GitHub Desktop.
Save eclipselu/da7b4670d6b9ddd6787124ed9ba94d97 to your computer and use it in GitHub Desktop.
Longest Substring with At Least K Repeating Characters
class Solution {
public:
int longestSubstring(string s, int k) {
vector<int> count = getCharCount(s);
for (int i = 0; i < count.size(); ++i) {
char ch = i + 'a';
if (count[i] > 0 && count[i] < k) {
int max_len = INT_MIN;
vector<string> splits = splitString(s, ch);
for (const string &ss: splits) {
max_len = max(max_len, longestSubstring(ss, k));
}
return max_len;
}
}
return s.length();
}
private:
vector<int> getCharCount(string s) {
vector<int> count(26, 0);
for (char ch: s)
++count[ch - 'a'];
return count;
}
vector<string> splitString(string s, char delim) {
vector<string> result;
vector<int> occurences;
int len = s.length();
for (int i = 0; i < len; ++i)
if (s[i] == delim)
occurences.push_back(i);
occurences.push_back(len);
int start = 0;
for (int idx: occurences) {
result.push_back(s.substr(start, idx - start));
start = idx + 1;
}
return result;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment