Count characters with same neighbors | C ++ implementation of above approach ; Function to count the characters with same adjacent characters ; if length is less than 3 then return length as there will be only two characters ; Traverse the string ; Increment the count if the previous and next character is same ; Return count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countChar ( string str ) { int n = str . length ( ) ; if ( n <= 2 ) return n ; int count = 2 ; for ( int i = 1 ; i < n - 1 ; i ++ ) if ( str [ i - 1 ] == str [ i + 1 ] ) count ++ ; return count ; } int main ( ) { string str = " egeeksk " ; cout << countChar ( str ) ; return 0 ; }