Longest Substring Program Without Repeating Character

By | July 27, 2024

Longest Substring Program Without Repeating Character It should return the Substring.

Ex: The String value is : “abcadx” , for that non-repeating substring is: “bcadx”. So here we removed ‘a’ in this program because it is repeated character in this string.

import java.util.LinkedHashSet;
import java.util.Set;

class LongestSubstringWithoutRepeatingCharacter {
  public static String longestSubstring(String str) {
    int length = str.length();
    int left = 0, right = 0, max = 0, start = 0;
    Set<Character> set = new LinkedHashSet<>();

    while (right < length) {
      if (!set.contains(str.charAt(right))) {
        set.add(str.charAt(right++));
        int currentSize = set.size();
        if (currentSize > max) {
          max = currentSize;
          start = left; // Update start only if we found a new max
        }
      } else {
        set.remove(str.charAt(left++));
      }
    }
    return str.substring(start, start + max);
  }

  public static void main(String[] args) {
    String str = "abcadx";
    String longSubstring = longestSubstring(str);
    System.out.println("The value is: " + longSubstring);
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *