Best solutions for Microsoft interview tasks. Longest Semi-Alternating Substring
Alexander Molchevskyi
Experienced Rust, C++, Web3, Blockchain, Embedded developer exploring new opportunities
Description:
Solution:
This task is similar to the task String Without 3 Identical Consecutive Letters but here we need to find a longest string which doesn't contains three identical consecutive characters and return it's length. To do this we need to pass through the given string and count it's characters, if we meet three identical consecutive characters we have to save the length of the processed substring as a longest substring and start to count from 1. When the whole string is processed just return the saved counter of the longest substring.
C++ code:
int solution(const string & s) { const int MAX_COUNT = 3; int s_len = s.length(); if(s_len < MAX_COUNT) { return s_len; } int count = 1, result = 1; // Scan whole string and count it's characters. for(int i = 1; i < s_len - 1; ++i) { // If we meet 3 consecutive characters if((s[i-1] == s[i]) && (s[i+1] == s[i])) { // save the counter as result if it is // bigger than the previous result result = max(result,count+1); // and drop the counter to 1 count = 1; } else { count++; } } // return maximal result return max(result,count+1); }
Repository with the full project you can find here: https://github.com/jolly-fellow/microsoft/tree/master/longest_semi-alternating_substring
Return to the table of contents.