Input: s ="1001", k =3Output: 4Explanation: We can obtain the following strings:- Applying no operation on the string gives s ="1001".- Applying one operation on the substring starting at index 0 gives s ="_**011**_ 1".- Applying one operation on the substring starting at index 1 gives s ="1 _**110**_ ".- Applying one operation on both the substrings starting at indices 0 and 1 gives s ="_**0000**_ ".It can be shown that we cannot obtain any other string, so the answer is4.
Example 2:
1
2
3
4
5
6
Input: s ="10110", k =5Output: 2Explanation: We can obtain the following strings:- Applying no operation on the string gives s ="10110".- Applying one operation on the whole string gives s ="01001".It can be shown that we cannot obtain any other string, so the answer is2.
Flipping any substring of length k is a linear operation (XOR with a mask). The set of all possible strings is the span of the initial string and all possible flip masks. The number of distinct strings is 2^d, where d is the number of independent flip masks (which is n-k+1 for k < n, or 2 for k = n).
#include<string>#include<cmath>usingnamespace std;
constint MOD =1e9+7;
classSolution {
public:int numberOfDistinctBinaryStrings(string s, int k) {
int n = s.size();
if (k == n) return2;
longlong res =1;
for (int i =0; i < n-k+1; ++i) res = (res*2)%MOD;
return res;
}
};
1
2
3
4
5
6
7
8
funcnumberOfDistinctBinaryStrings(sstring, kint) int {
n:= len(s)
mod:= int(1e9+7)
ifk==n { return2 }
res:=1fori:=0; i < n-k+1; i++ { res = (res*2)%mod }
returnres}
1
2
3
4
5
6
7
8
9
classSolution {
publicintnumberOfDistinctBinaryStrings(String s, int k) {
int n = s.length(), MOD = (int)1e9+7;
if (k == n) return 2;
long res = 1;
for (int i = 0; i < n-k+1; ++i) res = (res*2)%MOD;
return (int)res;
}
}
1
2
3
4
5
6
7
8
9
classSolution {
funnumberOfDistinctBinaryStrings(s: String, k: Int): Int {
val n = s.length; val MOD = 1_000_000_007
if (k == n) return2var res = 1L repeat(n-k+1) { res = (res*2)%MOD }
return res.toInt()
}
}
1
2
3
4
5
classSolution:
defnumberOfDistinctBinaryStrings(self, s: str, k: int) -> int:
n, MOD = len(s), 10**9+7if k == n: return2return pow(2, n-k+1, MOD)
1
2
3
4
5
6
7
8
9
impl Solution {
pubfnnumber_of_distinct_binary_strings(s: String, k: i32) -> i32 {
let n = s.len() asi32;
if k == n { return2; }
letmut res =1i64;
for _ in0..(n-k+1) { res = (res*2)%1_000_000_007; }
res asi32 }
}
1
2
3
4
5
6
7
functionnumberOfDistinctBinaryStrings(s: string, k: number):number {
constn=s.length, MOD=1e9+7;
if (k===n) return2;
letres=1;
for (leti=0; i<n-k+1; ++i) res= (res*2)%MOD;
returnres;
}