gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
Give simple, common, and optimised Java solution Longest Substring Without Repeat
- User
Give simple, common, and optimised Java solution
Longest Substring Without Repeat
- Assistant
To find the longest substring without repeating characters in Java, you can use the sliding window technique along with a HashMap or an array to store the last seen index of characters. Here's a simple and optimized solution:
javaimport java.util.HashMap; import java.util.Map; public class LongestSubstringWithoutRepeat { public static int lengthOfLongestSubstring(String s) { if (s == null || s.isEmpty()) { return 0; } Map<Character, Integer> charIndexMap = new HashMap<>(); int maxLength = 0; int start = 0; for (int end = 0; end < s.length(); end++) { char currentChar = s.charAt(end); if (charIndexMap.containsKey(currentChar)) { // Update the start of the window to the right of the last index of currentChar start = Math.max(start, charIndexMap.get(currentChar) + 1); } // Update the last seen index of the current character charIndexMap.put(currentChar, end); // Calculate the length of the current substring and update maxLength if needed maxLength = Math.max(maxLength, end - start + 1); } return maxLength; } public static void main(String[] args) { String input = "abcabcbb"; System.out.println("Length of longest substring without repeating characters: " + lengthOfLongestSubstring(input)); // Output: 3 input = "bbbbb"; System.out.println("Length of longest substring without repeating characters: " + lengthOfLongestSubstring(input)); // Output: 1 input = "pwwkew"; System.out.println("Length of longest substring without repeating characters: " + lengthOfLongestSubstring(input)); // Output: 3 } }Explanation:
- Sliding Window Technique: Maintain a window with two pointers,
startandend. Theendpointer moves over each character in the string, and thestartpointer ensures no duplicate characters exist in the current window. - HashMap: Store the last index of each character seen in the string. This allows quick lookup to check if a character has been seen before and to update the start of the window accordingly.
- Optimization: Only move the
startpointer forward and never backward, ensuring efficient calculation of the maximum substring length. - Time Complexity: O(n), where n is the length of the string. Each character is processed at most twice, once by
endpointer and once bystartpointer. - Space Complexity: O(min(n, m)), where n is the length of the string and m is the size of the character set.
This solution efficiently handles the problem using a well-optimized approach leveraging a hash map and a sliding window.
- Sliding Window Technique: Maintain a window with two pointers,