From 0f1dcbe47930d9a30f1beaee359c183669b4d1fb Mon Sep 17 00:00:00 2001 From: PANKAJ PATWAL <120747214+Chiefpatwal@users.noreply.github.com> Date: Sat, 26 Oct 2024 01:48:40 +0530 Subject: [PATCH] Add longest substring (#6007) --- ...stSubstringWithoutRepeatingCharacters.java | 46 +++++++++++++++++++ ...bstringWithoutRepeatingCharactersTest.java | 23 ++++++++++ 2 files changed, 69 insertions(+) create mode 100644 src/main/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharacters.java create mode 100644 src/test/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharactersTest.java diff --git a/src/main/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharacters.java b/src/main/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharacters.java new file mode 100644 index 000000000..0641730d8 --- /dev/null +++ b/src/main/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharacters.java @@ -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. + * + *
+ * 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