Longest Substring Without Repeating Characters
This program finds longest substring without repeating characters.
Problem Statement
Write a Java program to find longest substring without repeating characters.
Source Code
| 1 | import java.util.HashSet; |
| 2 | public class LongestSubstringNoRepeat { |
| 3 | public static void main(String[] args) { |
| 4 | System.out.println("Eduinq Longest Substring No Repeat"); |
| 5 | String str="abcabcbb"; |
| 6 | int maxLen=0; |
| 7 | for(int i=0;i<str.length();i++){ |
| 8 | HashSet<Character> set=new HashSet<>(); |
| 9 | for(int j=i;j<str.length();j++){ |
| 10 | if(set.contains(str.charAt(j))) break; |
| 11 | set.add(str.charAt(j)); |
| 12 | maxLen=Math.max(maxLen,j-i+1); |
| 13 | } |
| 14 | } |
| 15 | System.out.println("Longest substring length = "+maxLen); |
| 16 | } |
| 17 | } |
Program Output
Eduinq Longest Substring No Repeat Longest substring length = 3
Explanation
Nested loops check every possible substring while a HashSet tracks the characters seen so far in the current window, breaking as soon as a repeat is found, together finding the longest substring without repeating characters.