|
| 1 | +package com.thealgorithms.slidingwindow; |
| 2 | +import java.util.HashSet; |
| 3 | + |
| 4 | +/** |
| 5 | + * The Longest Substring Without Repeating Characters algorithm finds the length of |
| 6 | + * the longest substring without repeating characters in a given string. |
| 7 | + * |
| 8 | + * <p> |
| 9 | + * Worst-case performance O(n) |
| 10 | + * Best-case performance O(n) |
| 11 | + * Average performance O(n) |
| 12 | + * Worst-case space complexity O(min(n, m)), where n is the length of the string |
| 13 | + * and m is the size of the character set. |
| 14 | + * |
| 15 | + * @author (https://github.com/Chiefpatwal) |
| 16 | + */ |
| 17 | +public final class LongestSubstringWithoutRepeatingCharacters { |
| 18 | + |
| 19 | + // Prevent instantiation |
| 20 | + private LongestSubstringWithoutRepeatingCharacters() { |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * This method finds the length of the longest substring without repeating characters. |
| 25 | + * |
| 26 | + * @param s is the input string |
| 27 | + * @return the length of the longest substring without repeating characters |
| 28 | + */ |
| 29 | + public static int lengthOfLongestSubstring(String s) { |
| 30 | + int maxLength = 0; |
| 31 | + int left = 0; |
| 32 | + HashSet<Character> charSet = new HashSet<>(); |
| 33 | + |
| 34 | + for (int right = 0; right < s.length(); right++) { |
| 35 | + // If the character is already in the set, remove characters from the left |
| 36 | + while (charSet.contains(s.charAt(right))) { |
| 37 | + charSet.remove(s.charAt(left)); |
| 38 | + left++; |
| 39 | + } |
| 40 | + charSet.add(s.charAt(right)); |
| 41 | + maxLength = Math.max(maxLength, right - left + 1); |
| 42 | + } |
| 43 | + |
| 44 | + return maxLength; |
| 45 | + } |
| 46 | +} |
0 commit comments