3. Longest Substring Without Repeating Characters
Explanation:
To solve this problem, we can use the sliding window technique. We maintain a window that contains characters without repeating characters. We iterate through the string, keep track of the characters we have seen so far using a hashmap to store the index of the characters. If we encounter a character that is already in the window, we update the start index of the window to the next index of the repeated character. We update the maximum length of the substring as we iterate through the string.
- Initialize a hashmap to store characters and their indices.
- Initialize variables for the start index of the window, the maximum length of the substring, and the current index.
- Iterate through the string:
- Check if the character is in the hashmap and if its index is within the current window.
- If yes, update the start index of the window to the next index of the repeated character.
- Update the current character's index in the hashmap.
- Update the maximum length of the substring.
- Check if the character is in the hashmap and if its index is within the current window.
- Return the maximum length of the substring.
Time Complexity: O(n) where n is the length of the input string. Space Complexity: O(min(n, m)) where n is the length of the input string and m is the size of the character set.
:
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s == null || s.length() == 0) {
return 0;
}
Map<Character, Integer> charIndexMap = new HashMap<>();
int maxLength = 0;
int start = 0;
for (int end = 0; end < s.length(); end++) {
char c = s.charAt(end);
if (charIndexMap.containsKey(c) && charIndexMap.get(c) >= start) {
start = charIndexMap.get(c) + 1;
}
charIndexMap.put(c, end);
maxLength = Math.max(maxLength, end - start + 1);
}
return maxLength;
}
}
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.