Skip to content

Commit 18f78bb

Browse files
Added Leetcode Longest Substring Without Repeating Characters problem (dubesar#615)
1 parent c7d2e64 commit 18f78bb

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
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+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
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.

0 commit comments

Comments
 (0)