DEV Community

Debesh P.
Debesh P.

Posted on

3. Longest Substring Without Repeating Characters | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/longest-substring-without-repeating-characters/


Detailed Step-by-Step Explanation

https://leetcode.com/problems/longest-substring-without-repeating-characters/solutions/7460387/most-optimal-solution-sliding-window-has-qxth


leetcode 3


Solution

class Solution {
    public int lengthOfLongestSubstring(String s) {

        Map<Character, Integer> map = new HashMap<>();
        int left = 0;
        int maxLength = 0;

        for (int right = 0; right < s.length(); right++) {
            char ch = s.charAt(right);

            if (map.containsKey(ch)) {
                left = Math.max(left, map.get(ch) + 1);
            }

            map.put(ch, right);
            maxLength = Math.max(maxLength, right - left + 1);
        }

        return maxLength;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)