159. Longest Substring with At Most Two Distinct Characters
Explanation
Given a string, we are to find the length of the longest substring with at most two distinct characters. We can solve this problem using a sliding window approach. We can maintain a hashmap to store the frequency of characters in the current window and keep track of the distinct characters. As we iterate through the string, we update the window boundaries and keep track of the longest substring with at most two distinct characters.
- Initialize a hashmap to store the frequency of characters and two pointers to define the window boundaries.
- Iterate through the string:
- Update the frequency of the current character in the hashmap.
- If the size of the hashmap exceeds 2, we shrink the window from the left until the size becomes 2.
- Update the length of the longest substring.
- Return the length of the longest substring.
Time Complexity: O(N), where N is the length of the input string. Space Complexity: O(1) since the hashmap will have at most 3 characters.
class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int left = 0, right = 0, maxLen = 0;
Map<Character, Integer> map = new HashMap<>();
while (right < s.length()) {
map.put(s.charAt(right), map.getOrDefault(s.charAt(right), 0) + 1);
while (map.size() > 2) {
map.put(s.charAt(left), map.get(s.charAt(left)) - 1);
if (map.get(s.charAt(left)) == 0) {
map.remove(s.charAt(left));
}
left++;
}
maxLen = Math.max(maxLen, right - left + 1);
right++;
}
return maxLen;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.