Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- https://practice.geeksforgeeks.org/problems/equal-0-1-and-23208/1?page=1&difficulty[]=1&difficulty[]=2&status[]=unsolved&status[]=attempted&category[]=Strings&sortBy=submissions
- Given a string str of length N which consists of only 0, 1 or 2s, count the number of substring which have equal number of 0s, 1s and 2s.
- Example 1:
- Input: str = “0102010”
- Output: 2
- Explanation: Substring str[2, 4] = “102” and
- substring str[4, 6] = “201” has equal number
- of 0, 1 and 2
- Example 2:
- Input: str = “11100022”
- Output: 0
- Explanation: There is no substring with
- equal number of 0 , 1 and 2.
- ---------------------------------------------------------------------------------------------------------------------------------------
- class Solution{
- public:
- long long getSubstringWithEqual012(string str) {
- long long count =0;
- map<pair<long long,long long>,long long>mp;
- long long ones =0;
- long long zeros =0;
- long long twos =0;
- mp[{0,0}]=1;
- for(int i=0; i<str.length();i++){
- if(str[i]=='1'){
- ones++;
- }
- if(str[i]=='2'){
- twos++;
- }
- if(str[i]=='0'){
- zeros++;
- }
- pair<int,int>p = {zeros-ones,zeros-twos};
- mp[p]++;
- }
- return count;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment