Substring Problem
- Use two pointers, i and j, both of them start from the beginning
- j is the end, i is the begin
This is the logic:
Start from j and move it one step at a time from left to right
if the i - j substring meets the requirements check whether substring is the maximum
if the i - j substring not meet the requirements, move i and then keep checking
Please see the template,
following is the example of 159. Longest Substring with At Most Two Distinct Characters
class Solution(object):
def lengthOfLongestSubstringTwoDistinct(self, s):
"""
:type s: str
:rtype: int
"""
table = collections.Counter()
begin = 0
end = 0
counter = 0
maximum = 0
while end < len(s):
c = s[end]
table[c] += 1
if table[c] == 1:
counter += 1
end += 1
while counter > 2:
c = s[begin]
table[c] -= 1
if table[c] == 0:
counter -= 1
begin += 1
maximum = max(end-begin, maximum)
return maximum