- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- Find time taken for signal to reach all positions in a string in C++
- Optimal Account Balancing in C++
- Find time taken for signal to reach all positions in a string - C++
- Switching positions of selected characters in a string in JavaScript
- Count of Numbers in a Range divisible by m and having digit d in even positions in C++
- Balancing two arrays in JavaScript
- All ways of balancing n parenthesis in JavaScript
- Count Numbers in Range with difference between Sum of digits at even and odd positions as Prime in C++
- JavaScript: Balancing parentheses
- Explain the balancing parenthesis of PDA
- Positions of Large Groups in Python
- Program to get final string after shifting characters with given number of positions in Python
- C++ Program to Implement self Balancing Binary Search Tree
- Find max of two Rational numbers in C++
- Find and return array positions of multiple values JavaScript
