Count substrings of same length differing by a single character from two given strings | Java program for the above approach ; Function to count the number of subStrings of equal length which differ by a single character ; Stores the count of pairs of subStrings ; Traverse the String s ; Traverse the String t ; Different character ; Increment the answer ; Count equal subStrings from next index ; Increment the count ; Increment q ; Check the condition ; Increment k ; Add q to count ; Decrement z ; Return the final count ; Driver Code ; Function Call
class GFG { static int countSubStrings ( String s , String t ) { int answ = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { for ( int j = 0 ; j < t . length ( ) ; j ++ ) { if ( t . charAt ( j ) != s . charAt ( i ) ) { answ += 1 ; int k = 1 ; int z = - 1 ; int q = 1 ; while ( j + z >= 0 && 0 <= i + z && s . charAt ( i + z ) == t . charAt ( j + z ) ) { z -= 1 ; answ += 1 ; q += 1 ; } while ( s . length ( ) > i + k && j + k < t . length ( ) && s . charAt ( i + k ) == t . charAt ( j + k ) ) { k += 1 ; answ += q ; z = - 1 ; } } } } return answ ; } public static void main ( String [ ] args ) { String S = " aba " ; String T = " baba " ; System . out . println ( countSubStrings ( S , T ) ) ; } }