套路测试之Longest Substring with At Most Two Distinct Characters

套路测试之Longest Substring with At Most Two Distinct Characters_第1张图片


The main idea is to maintain a sliding window with 2 unique characters. The key is to store the last occurrence of each character as the value in the hashmap. This way, whenever the size of the hashmap exceeds 2, we can traverse through the map to find the character with the left most index, and remove 1 character from our map. Since the range of characters is constrained, we should be able to find the left most index in constant time.

套路测试之Longest Substring with At Most Two Distinct Characters_第2张图片

你可能感兴趣的:(套路测试之Longest Substring with At Most Two Distinct Characters)