I'm still new to C++ and tried one of the harder challenges on a coding practice/challenge website. The challenge was the following:
Given a string of digits, return the longest substring with alternating odd/even or even/odd digits. If two or more substrings have the same length, return the substring that occurs first.
I was able to solve it in ~ 50 minutes, but I feel like my code is really sloppy. Can anyone give me tips on how to simplify this? I find myself falling into very complex ways of solving things often.
std::string longestSubstring(std::string digits) {
std::string strOddEven{};
std::vector<std::string> vecOddEven{};
bool next{};
int maxSize{};
for (int i = 0; i < digits.size() - 1; ++i)
{
if ((digits.at(i) % 2 == 0 && digits.at(i + 1) % 2 != 0) ||
(digits.at(i) % 2 != 0 && digits.at(i + 1) % 2 == 0))
{
strOddEven += digits.at(i);
next = true;
if (i == digits.size() - 2) // add to strOddEven and push_back
{ // in case of longest string being at end
strOddEven += digits.at(i + 1);
vecOddEven.push_back(strOddEven);
}
}
else if (next)
{
strOddEven += digits.at(i);
vecOddEven.push_back(strOddEven);
strOddEven = "";
next = false;
}
}
for (auto& i : vecOddEven)
if (i.size() > maxSize)
maxSize = i.size();
for (auto& i : vecOddEven)
if (i.size() == maxSize)
return i;
}