3713. Longest Balanced Substring I
UnknownView on LeetCode
Time: O(n)
Space: O(n)
Advertisement
Approach
Find longest substring with equal 0s and 1s using prefix sum approach.
Key Techniques
String
String problems range from simple character counting to complex pattern matching. Common approaches include two pointers, sliding window, prefix hashing, and the KMP algorithm. In C#, strings are immutable — use StringBuilder for efficient concatenation inside loops.
3713.cs
C#
// Approach: Find longest substring with equal 0s and 1s using prefix sum approach.
// Time: O(n) Space: O(n)
public class Solution
{
public int LongestBalanced(string s)
{
int n = s.Length;
int[] cnt = new int[26];
int ans = 0;
for (int i = 0; i < n; ++i)
{
Array.Clear(cnt, 0, cnt.Length);
int mx = 0, v = 0;
for (int j = i; j < n; ++j)
{
int c = s[j] - 'a';
if (++cnt[c] == 1)
++v;
mx = Math.Max(mx, cnt[c]);
if (mx * v == j - i + 1)
ans = Math.Max(ans, j - i + 1);
}
}
return ans;
}
}Advertisement
Was this solution helpful?