Number of ways to remove a sub | Java program to count number of ways of removing a substring from a string such that all remaining characters are equal ; Function to return the number of ways of removing a sub - string from s such that all the remaining characters are same ; To store the count of prefix and suffix ; Loop to count prefix ; Loop to count suffix ; First and last characters of the string are same ; Otherwise ; Driver function
import java . util . * ; class solution { static int no_of_ways ( String s ) { int n = s . length ( ) ; int count_left = 0 , count_right = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( s . charAt ( i ) == s . charAt ( 0 ) ) { ++ count_left ; } else break ; } for ( int i = n - 1 ; i >= 0 ; -- i ) { if ( s . charAt ( i ) == s . charAt ( n - 1 ) ) { ++ count_right ; } else break ; } if ( s . charAt ( 0 ) == s . charAt ( n - 1 ) ) return ( ( count_left + 1 ) * ( count_right + 1 ) ) ; else return ( count_left + count_right + 1 ) ; } public static void main ( String args [ ] ) { String s = " geeksforgeeks " ; System . out . println ( no_of_ways ( s ) ) ; } }