1 class Solution
2 {
3 public:
4 int numSubarraysWithSum(vector<int>& A, int S)
5 {
6 if(S==0)
7 {
8 int result = 0;
9 int count = 0;
10 for(int i = 0; i < A.size(); i ++)
11 {
12 if(A[i]==0)
13 count ++;
14 else
15 {
16 result += (count+1)*count/2;
17 count = 0;
18 }
19 }
20 if(count)
21 {
22 result += (count+1)*count/2;
23 count = 0;
24 }
25 return result;
26 }
27 int totalResult = 0;
28
29 int left = 0,right = 0;
30 int oneSum = 0;
31 int result = 0;
32 for(; right < A.size(); right ++)
33 {
34 if(oneSum < S)
35 {
36 if(A[right]==1)
37 oneSum ++;
38 }
39 if(oneSum == S)
40 {
41 int leftResult = 1,rightResult = 1;
42 while(right != A.size()-1 && A[right+1]==0)
43 {
44 right ++;
45 rightResult ++;
46 }
47 if(A[left]==1)
48 ;
49 else
50 {
51 while(left < right && A[left+1]==0)
52 {
53 left ++;
54 leftResult ++;
55 }
56 left ++;
57 leftResult ++;
58 }
59 result += leftResult*rightResult;
60 left ++;
61 oneSum --;
62 }
63 }
64 return result;
65 }
66 };