gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
Give simple, common, and optimised Java solution static int…
- User
Give simple, common, and optimised Java solution
static int longestSubstringWithoutRepeat (String s) { // your code goes here
- Assistant
Give simple, common, and optimised Java solution
static int longestSubstringWithoutRepeat (String s) { // your code goes here
To solve the problem of finding the longest substring without repeating characters in a given string, you can use a sliding window approach with a hash map (or a simple array in this case since we're dealing with characters). This approach efficiently finds the solution in linear time, i.e., O(n), where n is the length of the string. Here's a simple and optimized Java solution:
import java.util.HashMap;
import java.util.Map;
public class Solution {
public static int longestSubstringWithoutRepeat(String s) {
if (s == null || s.length() == 0) {
return 0; // Early return for null or empty string
}
int maxLength = 0;
int start = 0;
Map<Character, Integer> charIndexMap = new HashMap<>();
for (int end = 0; end < s.length(); end++) {
char currentChar = s.charAt(end);
// If the character is already in the map and within the current window
if (charIndexMap.containsKey(currentChar) && charIndexMap.get(currentChar) >= start) {
// Move the start to one position after the last occurrence of the current character
start = charIndexMap.get(currentChar) + 1;
}
// Update the character's latest occurrence index
charIndexMap.put(currentChar, end);
// Calculate the length of the current substring without repeating characters
maxLength = Math.max(maxLength, end - start + 1);
}
return maxLength;
}
public static void main(String[] args) {
String testString = "abcabcbb";
System.out.println("Longest substring without repeating characters: " + longestSubstringWithoutRepeat(testString)); // Output: 3
}
}
Initialization:
maxLength keeps track of the longest substring found.start indicates the starting index of the current substring without repetition.charIndexMap stores the last index of each character encountered.Iteration:
end as the index.start to the index right after the last occurrence of this character.end.end - start + 1) and update maxLength if it's larger.Edge Cases:
This code efficiently finds the longest substring without repeating characters with just a single pass through the string and constant-time map operations.