1
+ // Runtime: 183 ms (Top 88.92%) | Memory: 20.50 MB (Top 92.45%)
2
+
1
3
class Solution {
2
4
public:
3
5
bool hasAllCodes (string s, int k) {
4
- if (s.size () < k)
6
+ int n=pow (2 ,k),m=s.size ();
7
+ vector<bool >check (n,0 ); // Check Array ,initially all value false;
8
+
9
+ int val=0 ; // Variable that will help in formation of binary to decimal value of every substring.
10
+ int i=0 ,j=0 ; // Sliding window ponter.
11
+
12
+ while (j<m)
5
13
{
6
- return false ;
7
- }
8
- unordered_set<string> binary_codes;
9
- for (int i = 0 ; i < s.size ()-k+1 ; i++)
10
- {
11
- string str = s.substr (i, k);
12
- binary_codes.insert (str);
13
- if (binary_codes.size () == (int )pow (2 , k))
14
+ val=val*2 +(s[j]-' 0' ); // Form Binary ,Make it decimal.
15
+
16
+ if (j-i+1 <k) // If window size is Less than k ,just j++;
17
+ j++;
18
+ else if (j-i+1 ==k) // If we hit k size.
14
19
{
15
- return true ;
20
+ check[val]=true ; // Mark check cval true.
21
+ val=val-(s[i]-' 0' )*(pow (2 ,k-1 )); // Remove ith value's Calucaltion .
22
+ i++; // Increment i
23
+ j++; // and Increment j to maintain size of window as k
16
24
}
17
25
}
18
- return false ;
26
+
27
+ for (int l=0 ;l<n;l++)
28
+ {
29
+ if (check[l]==false ) // If we didn't find any value ,means that susbtring is missing
30
+ return false ; // Return false;
31
+ }
32
+
33
+ return true ; // Return true;
19
34
}
20
- };
35
+ };
0 commit comments