Pankaj-Str / JAVA-SE-Tutorial-codeswithpankaj

Pankaj-Str's GitHub, 'JAVA-SE-Tutorial-codeswithpankaj,' is a concise compendium of Java SE tutorials. Ideal for developers and learners, it offers clear and insightful code snippets, providing an efficient pathway to enhance Java programming skills. A valuable resource for mastering essential concepts
https://codeswithpankaj.com
33 stars 15 forks source link

Create a Java program to find the longest substring without repeating characters in a given string. #2

Closed Pankaj-Str closed 1 year ago

Mumtazsk1424 commented 1 year ago
import java.util.HashMap;

public class LongestSubstringWithoutRepeatingChars {

    public static String findLongestSubstring(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }

        int maxLength = 0;
        int start = 0;
        int end = 0;
        int currentStart = 0;
        HashMap<Character, Integer> charIndexMap = new HashMap<>();

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if (charIndexMap.containsKey(c) && charIndexMap.get(c) >= currentStart) {
                currentStart = charIndexMap.get(c) + 1;
            }

            charIndexMap.put(c, i);

            if (i - currentStart > maxLength) {
                maxLength = i - currentStart;
                start = currentStart;
                end = i;
            }
        }

        return s.substring(start, end + 1);
    }

    public static void main(String[] args) {
        String input = "abcabcbb";
        String longestSubstring = findLongestSubstring(input);
        System.out.println("Longest substring without repeating characters: " + longestSubstring);
    }
}
AdityaSuryawanshi07 commented 1 year ago
public class LongestSubstringWithoutRepeatingChars {
    public static String findLongestSubstring(String s) {
        if (s == null || s.isEmpty()) {
            return "";
        }

        int n = s.length();
        int maxLength = 0;
        int start = 0;
        int end = 0;

        int[] charIndex = new int[256]; // Assuming ASCII characters

        for (int i = 0, j = 0; j < n; j++) {
            char currentChar = s.charAt(j);
            i = Math.max(charIndex[currentChar], i);

            if (j - i + 1 > maxLength) {
                maxLength = j - i + 1;
                start = i;
                end = j;
            }

            charIndex[currentChar] = j + 1;
        }

        return s.substring(start, end + 1);
    }

    public static void main(String[] args) {
        String input = "abcabcbb";
        String longestSubstring = findLongestSubstring(input);
        System.out.println("Longest substring without repeating characters: " + longestSubstring);
    }
}