------
## 最终结论
```python
def numSubarraysWithSum(A, S):
    count = 0
    current_sum = 0
    prefix_sum_count = {0: 1}  # Initialize with sum 0 having one occurrence

    for num in A:
        current_sum += num
        
        # Check if (current_sum - S) exists in the prefix_sum_count
        if (current_sum - S) in prefix_sum_count:
            count += prefix_sum_count[current_sum - S]
        
        # Update the frequency of current_sum in the dictionary
        if current_sum in prefix_sum_count:
            prefix_sum_count[current_sum] += 1
        else:
            prefix_sum_count[current_sum] = 1

    return count

# Example usage:
A = [1, 0, 1, 0, 1]
S = 2
print(numSubarraysWithSum(A, S))  # Output: 4
```