Skip to content

Commit 7edc96b

Browse files
committed
Implement Longest Substring Without Repeating Characters
1 parent 02a2934 commit 7edc96b

File tree

2 files changed

+69
-0
lines changed

2 files changed

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

0 commit comments

Comments
 (0)