Count substrings of same length differing by a single character from two given strings | C ++ pprogram 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubstrings ( string s , string t ) { int answ = 0 ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { for ( int j = 0 ; j < t . size ( ) ; j ++ ) { if ( t [ j ] != s [ i ] ) { answ += 1 ; int k = 1 ; int z = -1 ; int q = 1 ; while ( j + z >= 0 && 0 <= i + z && s [ i + z ] == t [ j + z ] ) { z -= 1 ; answ += 1 ; q += 1 ; } while ( s . size ( ) > i + k && j + k < t . size ( ) && s [ i + k ] == t [ j + k ] ) { k += 1 ; answ += q ; z = -1 ; } } } } return answ ; } int main ( ) { string S = " aba " ; string T = " baba " ; cout << ( countSubstrings ( S , T ) ) ; }