Maximum count of X that can be inserted with no 3 adjacent characters are X | Java program for the above approach ; Utility function to find maximum count of X that are to be inserted into str such that no three consecutive characters are equal to X ; Stores count of consecutive X ; Stores count of characters which is not equal to X ; Iterate over characters of string , str ; If current character is X ; Update countX ; If countX is less than 3 ; Update countNotX ; Update countX ; If countX is greater than or equal to 3 ; Function to find maximum count of X that are to be inserted into str such that no three consecutive characters are equal to X ; Print the answer ; Driver Code ; Given string ; Function Call
import java . util . * ; public class Main { static int maxNumberOfXAddedUtil ( String str , char X ) { int countX = 0 ; int countNotX = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str . charAt ( i ) == X ) { countX ++ ; } else if ( countX < 3 ) { countNotX ++ ; countX = 0 ; } } if ( countX >= 3 ) return - 1 ; else return 2 * ( countNotX + 1 ) - ( str . length ( ) - countNotX ) ; } static void maxNumberOfXAdded ( String str , char X ) { int ans = maxNumberOfXAddedUtil ( str , X ) ; System . out . println ( ans ) ; } public static void main ( String [ ] args ) { String str = " xxyxy " ; char X = X ; maxNumberOfXAdded ( str , X ) ; } }