
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Numbers of Balancing Positions in String in C++
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
#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