Quick actions

cmd+k|ctrl+k

Navigation

Languages

LongestSubstring

Snippet info

Language

Java

Visibility

public

Author

kranthi.mangani

Created

2026-02-13T06:55:08.75361Z

Updated

2026-02-13T07:18:37.120837Z


import java.util.*;

class Main {
    public static void main(String[] args) {
        System.out.println("Hello World!");
        String s="abbccbabc";
        System.out.print(lengthOfLongestSubstring(s));
        System.out.print(longestSubstring(s));
    }
    
 


    public static int lengthOfLongestSubstring(String s) {
        int[] last = new int[128];
        Arrays.fill(last, -1);
        int left = 0, max = 0;

        for (int right = 0; right < s.length(); right++) {
            char c = s.charAt(right);
            if (last[c] >= left) {
                left = last[c] + 1; // jump left past the previous occurrence
            }
            last[c] = right;
            max = Math.max(max, right - left + 1);
        }
        return max;
    }

    public static String longestSubstring(String s) {
        int[] last = new int[128];
        Arrays.fill(last, -1);
        int left = 0, max = 0, start = 0;

        for (int right = 0; right < s.length(); right++) {
            char c = s.charAt(right);
            if (last[c] >= left) {
                left = last[c] + 1;
            }
            last[c] = right;

            int curr = right - left + 1;
            if (curr > max) {
                max = curr;
                start = left;
            }
        }
        return s.substring(start, start + max);
    }

}
INFO