Check if a string is made up of K alternating characters | C ++ implementation of the approach ; Function to check if a string is made up of k alternating characters ; Check if all the characters at indices 0 to K - 1 are different ; If that bit is already set in checker , return false ; Otherwise update and continue by setting that bit in the checker ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isKAlternating ( string s , int k ) { if ( s . length ( ) < k ) return false ; int checker = 0 ; for ( int i = 0 ; i < k ; i ++ ) { int bitAtIndex = s [ i ] - ' a ' ; if ( ( checker & ( 1 << bitAtIndex ) ) > 0 ) { return false ; } checker = checker | ( 1 << bitAtIndex ) ; } for ( int i = k ; i < s . length ( ) ; i ++ ) if ( s [ i - k ] != s [ i ] ) return false ; return true ; } int main ( ) { string str = " acdeac " ; int K = 4 ; if ( isKAlternating ( str , K ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; }