File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ public class SubstringAnagrams {
2
+ public int substringAnagrams (String s , String t ) {
3
+ int lenS = s .length ();
4
+ int lenT = t .length ();
5
+ if (lenT > lenS ) return 0 ;
6
+ int count = 0 ;
7
+ int [] expectedFreqs = new int [26 ];
8
+ int [] windowFreqs = new int [26 ];
9
+ // Populate 'expected_freqs' with the characters in string 't'.
10
+ for (char c : t .toCharArray ()) {
11
+ expectedFreqs [c - 'a' ] += 1 ;
12
+ }
13
+ int left , right ;
14
+ left = right = 0 ;
15
+ while (right < lenS ) {
16
+ // Add the character at the right pointer to 'window_freqs'
17
+ // before sliding the window.
18
+ windowFreqs [s .charAt (right ) - 'a' ] += 1 ;
19
+ // If the window has reached the expected fixed length, we
20
+ // advance the left pointer as well as the right pointer to
21
+ // slide the window.
22
+ if (right - left + 1 == lenT ) {
23
+ if (compareFreqs (windowFreqs , expectedFreqs )) {
24
+ count += 1 ;
25
+ }
26
+ // Remove the character at the left pointer from
27
+ // 'window_freqs' before advancing the left pointer.
28
+ windowFreqs [s .charAt (left ) - 'a' ] -= 1 ;
29
+ left += 1 ;
30
+ }
31
+ right += 1 ;
32
+ }
33
+ return count ;
34
+ }
35
+
36
+ private boolean compareFreqs (int [] windowFreqs , int [] expectedFreqs ) {
37
+ for (int i = 0 ; i < 26 ; i ++) {
38
+ if (windowFreqs [i ] != expectedFreqs [i ]) return false ;
39
+ }
40
+ return true ;
41
+ }
42
+ }
You can’t perform that action at this time.
0 commit comments