Minimum operations required to convert all characters of a String to a given Character | C ++ program to implement the above approach ; Function to find the minimum number of operations required ; Maximum number of characters that can be changed in one operation ; If length of the string less than maximum number of characters that can be changed in an operation ; Set the last index as the index for the operation ; Otherwise ; If size of the string is equal to the maximum number of characters in an operation ; Find the number of operations required ; Find the starting position ; Print i - th index ; Shift to next index ; Otherwise ; Find the number of operations required ; If n % div exceeds k ; Print i - th index ; Shift to next index ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countOperations ( int n , int k ) { int div = 2 * k + 1 ; if ( n / 2 <= k ) { cout << 1 << " STRNEWLINE " ; if ( n > k ) cout << k + 1 ; else cout << n ; } else { if ( n % div == 0 ) { int oprn = n / div ; cout << oprn << " STRNEWLINE " ; int pos = k + 1 ; cout << pos << " ▁ " ; for ( int i = 1 ; i <= oprn ; i ++ ) { cout << pos << " ▁ " ; pos += div ; } } else { int oprn = n / div + 1 ; cout << oprn << " STRNEWLINE " ; int pos = n % div ; if ( n % div > k ) pos -= k ; for ( int i = 1 ; i <= oprn ; i ++ ) { cout << pos << " ▁ " ; pos += div ; } } } } int main ( ) { string str = " edfreqwsazxet " ; char ch = ' $ ' ; int n = str . size ( ) ; int k = 4 ; countOperations ( n , k ) ; return 0 ; }