Finding the longest substring with unique characters.
Here’s a Java program that finds the longest substring with unique characters:
import java.util.HashSet; public class LongestSubstring { public static String findLongestSubstring(String input) { if (input == null || input.isEmpty()) { return ""; } int n = input.length(); int maxLength = 0; int start = 0; int end = 0; HashSet<Character> set = new HashSet<>(); while (end < n) { char c = input.charAt(end); if (!set.contains(c)) { set.add(c); if (end - start + 1 > maxLength) { maxLength = end - start + 1; } end++; } else { set.remove(input.charAt(start)); start++; } } return input.substring(start, start + maxLength); } public static void main(String[] args) { String input = "abcabcbb"; String longestSubstring = findLongestSubstring(input); System.out.println("Longest substring with unique characters: " + longestSubstring); } }
In this program, we use a sliding window approach to find the longest substring with unique characters. We maintain a set to keep track of the characters in the current window. If a character is not present in the set, we add it and update the maximum length. If a character is already in the set, we remove the character at the start of the window and move the start pointer forward.
The `findLongestSubstring` method takes an input string and returns the longest substring with unique characters. In the `main` method, we demonstrate its usage by finding the longest substring in the string “abcabcbb” and printing the result.
When you run the program, it will output:
Longest substring with unique characters: abc
This means the longest substring with unique characters in the input string “abcabcbb” is “abc”.