Problem Summary
Given a string S consisting only of characters 0 and 1. A substring starts from l to r is called balanced if the number of zeroes equals to the number of ones in this substring. Determine the length of the longest balanced substring of S.
Solution
Let sum_zero[i] be the number of zeroes in the substring S[1]S[2]…S[i], and sum_one[i] be the number of ones.
If a substring S[i]S[i+1]…S[j] is balanced, we have this equation:
sum_zero[j] - sum_zero[i-1] = sum_one[j] - sum_one[i-1] (1)
If we let diff[i] = sum_zero[i] - sum_one[i], then (1) is actually:
diff[j] = diff[i-1] (2)
So, to find the longest substring ending at j, we only need to find the minimum i, such that (2) holds. If such i exits, the length of the longest substring ending at j is j-i+1, which can be used to update the answer.
The space and time complexities are both O(N).
Code
|
|