- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 61 lines of Python from the credited upstream file longest-balanced-substring-ii.py.
- The implementation visibly relies on hash lookup.
- No explicit loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4import collections5 6 78class Solution(object):9 def longestBalanced(self, s):10 """11 :type s: str12 :rtype: int13 """14 def count1():15 result = cnt = 016 for i in xrange(len(s)):17 cnt += 118 if i+1 == len(s) or s[i+1] != s[i]:19 result = max(result, cnt)20 cnt = 021 return result22 23 def count2(a, b):24 result = cnt = 025 lookup = collections.defaultdict(int, {cnt:-1})26 for i, x in enumerate(s):27 if x == a:28 cnt += 129 elif x == b:30 cnt -= 131 else:32 cnt = 033 lookup = collections.defaultdict(int, {cnt:i})34 continue35 if cnt in lookup:36 result = max(result, i-lookup[cnt])37 else:38 lookup[cnt] = i39 return result40 41 def count3():42 result = a = b = 043 lookup = collections.defaultdict(int, {(a, b):-1})44 for i, x in enumerate(s):45 if x == 'a':46 a += 147 elif x == 'b':48 b += 149 else:50 a -= 151 b -= 152 if (a, b) in lookup:53 result = max(result, i-lookup[a, b])54 else:55 lookup[a, b] = i56 return result57 58 return max(count1(), 59 count2('a', 'b'), count2('b', 'c'), count2('c', 'a'),60 count3())61