Longest Unique Substring
This program finds longest substring with unique characters.
Problem Statement
Write a Java program to find longest substring with unique characters in "abcabcbb".
Source Code
| 1 | import java.util.HashSet; |
| 2 | public class LongestUniqueSubstring { |
| 3 | public static void main(String[] args) { |
| 4 | System.out.println("Eduinq Longest Unique Substring"); |
| 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 unique substring length = "+maxLen); |
| 16 | } |
| 17 | } |
Program Output
Eduinq Longest Unique Substring Longest unique substring length = 3
Explanation
Nested loops generate every possible substring while a HashSet ensures each character is unique within the current window, breaking on any repeat, together finding the longest substring with unique characters.