Skip to content

Add longest substring #6007

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Oct 25, 2024
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.thealgorithms.slidingwindow;
import java.util.HashSet;

/**
* The Longest Substring Without Repeating Characters algorithm finds the length of
* the longest substring without repeating characters in a given string.
*
* <p>
* Worst-case performance O(n)
* Best-case performance O(n)
* Average performance O(n)
* Worst-case space complexity O(min(n, m)), where n is the length of the string
* and m is the size of the character set.
*
* @author (https://github.com/Chiefpatwal)
*/
public final class LongestSubstringWithoutRepeatingCharacters {

// Prevent instantiation
private LongestSubstringWithoutRepeatingCharacters() {
}

/**
* This method finds the length of the longest substring without repeating characters.
*
* @param s is the input string
* @return the length of the longest substring without repeating characters
*/
public static int lengthOfLongestSubstring(String s) {
int maxLength = 0;
int left = 0;
HashSet<Character> charSet = new HashSet<>();

for (int right = 0; right < s.length(); right++) {
// If the character is already in the set, remove characters from the left
while (charSet.contains(s.charAt(right))) {
charSet.remove(s.charAt(left));
left++;
}
charSet.add(s.charAt(right));
maxLength = Math.max(maxLength, right - left + 1);
}

return maxLength;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.thealgorithms.slidingwindow;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;

/**
* Unit tests for the LongestSubstringWithoutRepeatingCharacters class.
*
* @author (https://github.com/Chiefpatwal)
*/
public class LongestSubstringWithoutRepeatingCharactersTest {

@Test
public void testLengthOfLongestSubstring() {
// Test cases for the lengthOfLongestSubstring method
assertEquals(3, LongestSubstringWithoutRepeatingCharacters.lengthOfLongestSubstring("abcabcbb"));
assertEquals(1, LongestSubstringWithoutRepeatingCharacters.lengthOfLongestSubstring("bbbbb"));
assertEquals(3, LongestSubstringWithoutRepeatingCharacters.lengthOfLongestSubstring("pwwkew"));
assertEquals(0, LongestSubstringWithoutRepeatingCharacters.lengthOfLongestSubstring(""));
assertEquals(5, LongestSubstringWithoutRepeatingCharacters.lengthOfLongestSubstring("abcde"));
}
}