File tree Expand file tree Collapse file tree 2 files changed +45
-0
lines changed
LeetCode/Top 100 Liked/Longest Substring Without Repeating Characters Expand file tree Collapse file tree 2 files changed +45
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .*;
2+
3+ class Solution {
4+ public int lengthOfLongestSubstring (String s ) {
5+ // Map to store the character and its latest idx while traversing the string from left to right
6+ Map <Character , Integer > map = new HashMap <>();
7+ int max =0 ;
8+
9+ // i == start position of window
10+ // j = curr/end position of window being explored
11+ for (int i =0 , j =0 ; j < s .length (); j ++){
12+ char c = s .charAt (j );
13+ // If the current character has previously been seen and
14+ // the previous occurrence (idx) of the char >= the starting position of the window to be explored (i)
15+ if (map .containsKey (c ) && map .get (c ) >= i )
16+ i = map .get (c ) + 1 ;
17+ int currWindow = j -i +1 ;
18+ max = Math .max (currWindow , max );
19+ map .put (c , j );
20+ }
21+ return max ;
22+ }
23+ }
Original file line number Diff line number Diff line change 1+ Given a string s, find the length of the longest substring without repeating characters.
2+
3+ Example 1:
4+ Input: s = "abcabcbb"
5+ Output: 3
6+ Explanation: The answer is "abc", with the length of 3.
7+
8+ Example 2:
9+ Input: s = "bbbbb"
10+ Output: 1
11+ Explanation: The answer is "b", with the length of 1.
12+
13+ Example 3:
14+ Input: s = "pwwkew"
15+ Output: 3
16+ Explanation: The answer is "wke", with the length of 3.
17+ Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
18+
19+
20+ Constraints:
21+ 0 <= s.length <= 5 * 104
22+ s consists of English letters, digits, symbols and spaces.
You can’t perform that action at this time.
0 commit comments