Java Program To Find Longest Substring Without Repeating Characters In Java :-

Going to write a java program to find the longest substring without repeating characters in a given string. For example, if user input “Tutorialspoint4all.com” as a input string, then the longest substring without repeating or duplicate characters is “Tutorialsp” and its length is 10.

Java Program To Find Longest Substring Without Repeating Characters :-

/*Java Program to find longest substring without repeating characters*/ import java.util.*; import java.util.HashSet; public class Main { public static String longestSubstring(String Input_String){ HashSet<Character> set = new HashSet<Character>(); String longestOverAll = ""; String longestTillNow = ""; for (int j = 0; j < Input_String.length(); j++) { char c = Input_String.charAt(j); if (set.contains(c)) { longestTillNow = ""; set.clear(); } longestTillNow += c; set.add(c); if (longestTillNow.length() > longestOverAll.length()) { longestOverAll = longestTillNow; } } return longestOverAll; } public static int lengthOfLongestSubstring(String Input_String) { int len = Input_String.length(); Set<Character> set = new HashSet<>(); int substring_length = 0, i = 0, j = 0; while (i < len && j < len) { // try to extend the range [i, j] if (!set.contains(Input_String.charAt(j))){ set.add(Input_String.charAt(j++)); substring_length = Math.max(substring_length, j - i); } else { set.remove(Input_String.charAt(i++)); } } return substring_length; } public static void main(String[] args) { System.out.println("Enter your Input String: "); Scanner scanner = new Scanner(System.in); String Input_String = scanner.nextLine(); System.out.println("Your Longest String is " + Input_String); System.out.println("The longest Substring Length is : - " + lengthOfLongestSubstring(Input_String)); System.out.println("The longest Substring is :- "+ longestSubstring(Input_String)); } }

Output:-