Check if the given string is K | CPP implementation of the approach ; Function that return true if sub - string of length k starting at index i is also a prefix of the string ; k length sub - string cannot start at index i ; Character mismatch between the prefix and the sub - string starting at index i ; Function that returns true if str is K - periodic ; Check whether all the sub - strings str [ 0 , k - 1 ] , str [ k , 2 k - 1 ] ... are equal to the k length prefix of the string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrefix ( string str , int len , int i , int k ) { if ( i + k > len ) return false ; for ( int j = 0 ; j < k ; j ++ ) { if ( str [ i ] != str [ j ] ) return false ; i ++ ; } return true ; } bool isKPeriodic ( string str , int len , int k ) { for ( int i = k ; i < len ; i += k ) if ( ! isPrefix ( str , len , i , k ) ) return false ; return true ; } int main ( ) { string str = " geeksgeeks " ; int len = str . length ( ) ; int k = 5 ; if ( isKPeriodic ( str , len , k ) ) cout << ( " Yes " ) ; else cout << ( " No " ) ; }