Created
April 18, 2019 13:16
-
-
Save gladilindv/3b6222558134805beb06f2c40c5c992c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// only for one-byte encoding | |
string get2CharSubString(const string& s) { | |
auto l = s.length(); | |
if (l < 3) return s; | |
size_t p = 0; // start max substr position | |
size_t m = 0; // current max length of substr | |
char c1 = s[0]; | |
char c2 = '\0'; | |
for (size_t i = 1; i < l; i++) { | |
// cout << "new step, start pos=" << i << " for char=" << c1 << endl; | |
if (s[i] != c1) { | |
c2 = s[i]; | |
// we have two different chars and start index for search | |
// search to the left | |
size_t cntLeft = 0; | |
for (int j = i - 1; j >= 0; j--) { | |
if (s[j] == c1 || s[j] == c2) { | |
cntLeft++; | |
continue; | |
} | |
break; | |
} | |
// search to the right | |
size_t cntRight = 0; | |
for (size_t j = i + 1; j < l; j++) { | |
if (s[j] == c1 || s[j] == c2) { | |
cntRight++; | |
continue; | |
} | |
break; | |
} | |
// update max | |
if (m < cntLeft + cntRight + 1) { | |
p = i - cntLeft; | |
m = cntLeft + cntRight + 1; // 1 = current char | |
} | |
//cout << "p=" << p << " len=" << m << "[" << cntLeft << "," << cntRight << "] [" << c1 << "," << c2 << "]\n"; | |
// update vars | |
i += cntRight; | |
c1 = c2; | |
} | |
} | |
return string(s.c_str() + p, m); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment