titan2400

Longest Substring Without Repeating Characters - LeetCode

Nov 9th, 2025
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.25 KB | Source Code | 0 0
  1. // Longest Substring Without Repeating Characters - https://leetcode.com/problems/longest-substring-without-repeating-characters/description/
  2.  
  3. class Solution {
  4.     // Brute Force
  5.     // Time Complexity: O(n^2)
  6.     // Space Complexity: O(m) where m is length of longest substring
  7.     // public int lengthOfLongestSubstring(String s) {
  8.     //     int maxLength = 0;
  9.  
  10.     //     for(int i = 0; i < s.length(); i++) {
  11.     //         int len = 1;
  12.     //         Set<Character> set = new HashSet<>();
  13.     //         set.add(s.charAt(i));
  14.     //         for(int j = i+1; j < s.length(); j++) {
  15.     //             if (set.contains(s.charAt(j))) {
  16.     //                 break;
  17.     //             }
  18.     //             else {
  19.     //                 set.add(s.charAt(j));
  20.     //                 len++;
  21.     //             }
  22.     //         }
  23.  
  24.     //         maxLength = Math.max(len, maxLength);
  25.     //     }
  26.     //     return maxLength;
  27.     // }
  28.  
  29.     // Sliding Window
  30.     // Time Complexity: O(n)
  31.     // Space Complexity: O(m) where m is length of longest substring
  32.     // public int lengthOfLongestSubstring(String s) {
  33.     //     int maxLength = 0;
  34.     //     int left = 0, right = 0;
  35.     //     Set<Character> set = new HashSet<>();
  36.     //     for(int i = 0; i < s.length(); i++) {
  37.     //         while(set.contains(s.charAt(i))) {
  38.     //             set.remove(s.charAt(left));
  39.     //             left++;
  40.     //         }
  41.  
  42.     //         set.add(s.charAt(i));
  43.     //         maxLength = Math.max(right - left + 1, maxLength);
  44.     //         right++;
  45.     //     }
  46.     //     return maxLength;
  47.     // }
  48.  
  49.     // Sliding Window (Optimised)
  50.     // Time Complexity: O(n)
  51.     // Space Complexity: O(m) where m is length of longest substring
  52.     public int lengthOfLongestSubstring(String s) {
  53.         int maxLength = 0;
  54.         int left = 0;
  55.         Map<Character, Integer> map = new HashMap<>();
  56.         for(int right = 0; right < s.length(); right++) {
  57.  
  58.             if(map.containsKey(s.charAt(right))) {
  59.                 left = Math.max(map.get(s.charAt(right)) + 1, left);
  60.             }
  61.            
  62.             map.put(s.charAt(right), right);
  63.             maxLength = Math.max(right - left + 1, maxLength);
  64.         }
  65.         return maxLength;
  66.     }
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment