Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
934 B
4
Indexable
Never
class Solution {
        public static int lengthOfLongestSubstring(String s) {
        int n = s.length();
        int maxLength = 0;

        // Map to store the last index of each character in the string
        HashMap<Character, Integer> charIndexMap = new HashMap<>();

        // Start pointer of the sliding window
        int start = 0;

        for (int end = 0; end < n; end++) {
            char currentChar = s.charAt(end);

            // If the character is already in the substring, update the start pointer
            if (charIndexMap.containsKey(currentChar)) {
                start = Math.max(charIndexMap.get(currentChar) + 1, start);
            }

            // Update the maximum length
            maxLength = Math.max(maxLength, end - start + 1);

            // Update the last index of the current character
            charIndexMap.put(currentChar, end);
        }

        return maxLength;
    }
}