Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Finding the Longest Substring Without Repeating Characters in Java

Tech 2

Given a string s, find the length of the longest substring that does not contain any repeating charactesr.

Example 1:

Input: s = "abcabcbb"
Output: 3
Explanation: The longest substring without repeating characters is "abc", which has a length of 3.

Example 2:

Input: s = "bbbbb"
Output: 1
Explanation: The longest substring is "b", with length 1.

Example 3:

Input: s = "pwwkew"
Output: 3
Explanation: The longest substring is "wke", with length 3. Note that "pwke" is a subsequence, not a substring.

Approach 1: Two-Poiter Sliding Window

This method uses two pointers to define a sliding window and an array to track character posisions.

public class LongestUniqueSubstring {
    public static void main(String[] args) {
        String testStr = "abcabcbb";
        Solution solver = new Solution();
        int result = solver.findLongestUniqueSubstring(testStr);
        System.out.println("Length of longest unique substring: " + result);
    }
}

class Solution {
    public int findLongestUniqueSubstring(String s) {
        if (s == null || s.length() == 0) return 0;
        
        int[] lastSeenIndex = new int[128]; // Assuming ASCII characters
        for (int i = 0; i < 128; i++) {
            lastSeenIndex[i] = -1;
        }
        
        int maxLength = 0;
        int windowStart = 0;
        
        for (int windowEnd = 0; windowEnd < s.length(); windowEnd++) {
            char currentChar = s.charAt(windowEnd);
            int prevIndex = lastSeenIndex[currentChar];
            
            if (prevIndex >= windowStart) {
                windowStart = prevIndex + 1;
            }
            
            lastSeenIndex[currentChar] = windowEnd;
            maxLength = Math.max(maxLength, windowEnd - windowStart + 1);
        }
        
        return maxLength;
    }
}

Aproach 2: HashSet-Based Sliding Window

This approach uses a HashSet to track characters in the current window and adjusts the window dynamically.

import java.util.HashSet;
import java.util.Set;

public class LongestUniqueSubstringHashSet {
    public static void main(String[] args) {
        String input = "abcabcbb";
        SubstringFinder finder = new SubstringFinder();
        int length = finder.calculateMaxUniqueLength(input);
        System.out.println("Maximum length of unique substring: " + length);
    }
}

class SubstringFinder {
    public int calculateMaxUniqueLength(String str) {
        Set<Character> charSet = new HashSet<>();
        int strLen = str.length();
        int right = -1;
        int maxLen = 0;
        
        for (int left = 0; left < strLen; ++left) {
            if (left != 0) {
                charSet.remove(str.charAt(left - 1));
            }
            
            while (right + 1 < strLen && !charSet.contains(str.charAt(right + 1))) {
                charSet.add(str.charAt(right + 1));
                ++right;
            }
            
            maxLen = Math.max(maxLen, right - left + 1);
        }
        
        return maxLen;
    }
}
Tags: Java

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.