Posts Longest Distinct characters in string (geeksforgeeks - SDE Sheet)
Post
Cancel

Longest Distinct characters in string (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

Given a string S, find the length of the longest substring with all distinct characters.

geeksforgeeks

SOLUTION

This can be solved using sliding window. Maintain a HashSet to check the characters which have been visited.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution{

    static int longestSubstrDistinctChars(String s){

        int n = s.length();

        int l = 0;
        int r = 0;

        Set<Character> set = new HashSet<>();

        int maxLength = 0;

        while(r < n){

            char ch = s.charAt(r);

            if(!set.contains(ch)){

                maxLength = Math.max(maxLength, r-l+1);

                set.add(ch);

            }else{

                while(set.contains(ch)){
                    set.remove(s.charAt(l));
                    l++;
                }

                set.add(ch);

            }

            r++;

        }

        return maxLength;

    }

}
This post is licensed under CC BY 4.0 by the author.