Binary String
Problemβ
Given a binary string S. The task is to count the number of substrings that start and end with 1. For example, if the input string is β00100101β, then there are three substrings β1001β, β100101β and β101β.
Examples:β
Example 1:
Input:
N = 4
S = 1111
Output: 6
Explanation: There are 6 substrings from the given string. They are 11, 11, 11, 111, 111, 1111.
Example 2:
Input:
N = 5
S = 01101
Output: 3
Explanation: There 3 substrings from the given string. They are 11, 101, 1101.
Your task:β
The task is to complete the function binarySubstring() which takes the length of binary string n and a binary string a as input parameter and counts the number of substrings starting and ending with 1 and returns the count.
- Expected Time Complexity:
- Expected Auxiliary Space:
Constraints:β
Solutionβ
Pythonβ
def binarySubstring(self,n,s):
m = 0
for i in range(0, n):
if (s[i] == '1'):
m = m + 1
return m * (m - 1) // 2
Javaβ
public static int binarySubstring(int a, String str) {
int m = 0;
for (int i = 0; i < a; i++) {
if (str.charAt(i) == '1') {
m = m + 1;
}
}
return m * (m - 1) / 2;
}
C++β
long binarySubstring(int n, string a){
int m = 0;
for (int i = 0; i < n; i++) {
if (a[i] == '1') {
m = m + 1;
}
}
return m * (m - 1) / 2;
}
Cβ
long binarySubstring(int n, const char *a) {
int m = 0;
for (int i = 0; i < n; i++) {
if (a[i] == '1') {
m = m + 1;
}
}
return (long)m * (m - 1) / 2;
}
- Time Complexity:
- Auxiliary Space: