Skip to content

Commit 0f1dcbe

Browse files
authored
Add longest substring (#6007)
1 parent 135fb08 commit 0f1dcbe

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.thealgorithms.slidingwindow;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
/**
8+
* Unit tests for the LongestSubstringWithoutRepeatingCharacters class.
9+
*
10+
* @author (https://github.com/Chiefpatwal)
11+
*/
12+
public class LongestSubstringWithoutRepeatingCharactersTest {
13+
14+
@Test
15+
public void testLengthOfLongestSubstring() {
16+
// Test cases for the lengthOfLongestSubstring method
17+
assertEquals(3, LongestSubstringWithoutRepeatingCharacters.lengthOfLongestSubstring("abcabcbb"));
18+
assertEquals(1, LongestSubstringWithoutRepeatingCharacters.lengthOfLongestSubstring("bbbbb"));
19+
assertEquals(3, LongestSubstringWithoutRepeatingCharacters.lengthOfLongestSubstring("pwwkew"));
20+
assertEquals(0, LongestSubstringWithoutRepeatingCharacters.lengthOfLongestSubstring(""));
21+
assertEquals(5, LongestSubstringWithoutRepeatingCharacters.lengthOfLongestSubstring("abcde"));
22+
}
23+
}

0 commit comments

Comments
 (0)