|
| 1 | +/* |
| 2 | +link:- https://practice.geeksforgeeks.org/problems/binary-string-1587115620/1 |
| 3 | +problem: |
| 4 | +Given a binary string S. The task is to count the number of substrings that start and end with 1. |
| 5 | +For example, if the input string is "00100101", then there are three substrings "1001", "100101" and "101". |
| 6 | + |
| 7 | +Input: |
| 8 | +N = 4 |
| 9 | +S = 1111 |
| 10 | +Output: 6 |
| 11 | +Explanation: There are 6 substrings from |
| 12 | +the given string. They are 11, 11, 11, |
| 13 | +111, 111, 1111. |
| 14 | + |
| 15 | +Input: |
| 16 | +N = 5 |
| 17 | +S = 01101 |
| 18 | +Output: 3 |
| 19 | +Explanation: There 3 substrings from the |
| 20 | +given string. They are 11, 101, 1101. |
| 21 | + |
| 22 | +*/ |
| 23 | + |
| 24 | +class Solution |
| 25 | +{ |
| 26 | + public: |
| 27 | + //Function to count the number of substrings that start and end with 1. |
| 28 | + long binarySubstring(int n, string a){ |
| 29 | + |
| 30 | + // n = length of string , a = binary string |
| 31 | + int ans=0; |
| 32 | + sort(a.begin(),a.end()); |
| 33 | + for(int i=0;i<n;i++) |
| 34 | + { |
| 35 | + if(a[i]!='0') |
| 36 | + { |
| 37 | + ans++; |
| 38 | + } |
| 39 | + //ans= count(a.begin(), a.end(), '1'); |
| 40 | + } |
| 41 | + // return count; |
| 42 | + return (ans*(ans-1))/2; |
| 43 | + } |
| 44 | + |
| 45 | +}; |
| 46 | + |
| 47 | + |
| 48 | +/* |
| 49 | + |
| 50 | +approch:- |
| 51 | + |
| 52 | +1.count the total number of 1's in the string ( using sort string and for loop) |
| 53 | +2. observe pattern if |
| 54 | +number of 1 is 1 then ans 1 |
| 55 | +number of 1 is 2 then ans 2 |
| 56 | +number of 1 is 3 then ans 3 |
| 57 | +number of 1 is 4 then ans 6 |
| 58 | +number of 1 is 5 then ans 10 |
| 59 | +. |
| 60 | +. |
| 61 | +number of 1 is n then ans n*(n-1)/2 |
| 62 | + |
| 63 | +*/ |
| 64 | + |
0 commit comments