Given a binary string S, your work is to count the number of such substrings that start and end with 1, if there is no such combination print 0.
For Example:
You are given a string 01101, the total number of substrings that starts and ends with 1 is 11, 101, and 1101.
Example:
Input: n = 5, s = "01101"
Output: 3
Approach
C++
#include <bits/stdc++.h>using namespace std;int binary(int n, string s){int i = 0, j = n - 1;while (s[i] == '0')i++;while (s[j] == '0')j--;int cnt = 0;while (true){while (i < j){if (s[j] == '1')cnt++;j--;}i = i + 1;j = s.size() - 1;while (s[i] == '0')i++;if (i == j)break;}return cnt;}int main(){int n = 5;string s = "01101";cout << binary(n, s) << "\n";return 0;}
No comments:
Post a Comment