Find numbers of balancing positions in string in C++

C++Server Side ProgrammingProgramming

Suppose we have a string. We have to find the balancing position count in that string from where left and right part of the string contains same characters. The frequency of characters does not matter. So if the string is “ABAABA”, then the number of balancing positions is 3. These positions are AB|AABA, ABA|ABA, ABAA|BA.

To solve this, we will follow some efficient approach. After traversing the string we first feel right[] with counts of all characters. Then traverse the string from left to right. For every character we increment its count in left[] and decrement the count in right. For any point being traversed, if all characters that have non-zero values in left also have non-zero value in right, and vice versa is also true. Then increment the result.

Example

 Live Demo

#include <iostream>
#include <algorithm>
#define MAX_CHAR 256
using namespace std;
int countBalancePoints(string str) {
   int left[MAX_CHAR] = {0};
   int right[MAX_CHAR] = {0};
   for (int i=0; i<str.length(); i++)
   right[str[i]]++;
   int count = 0;
   for (int i=0; i < str.length() ; i++) {
      left[str[i]]++;
      right[str[i]]--;
      int j;
      for (j=0; j<MAX_CHAR; j++) {
         if ( (left[j] == 0 && right[j] != 0) || (left[j] != 0 && right[j] == 0))
         break;
      }
      if (j == MAX_CHAR)
         count++;
   }
   return count;
}
int main() {
   char str[] = "ABAABA";
   cout << "Number of balance points: " << countBalancePoints(str);
}

Output

Number of balance points: 3
raja
Published on 03-Jan-2020 10:44:58
Advertisements