Skip to content

Commit 6aadb7b

Browse files
committed
non repat substr
1 parent 04ec8fc commit 6aadb7b

File tree

2 files changed

+56
-1
lines changed

2 files changed

+56
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*
2+
Longest Substring Without Repeating Characters
3+
==============================================
4+
5+
Given a string s, find the length of the longest substring without repeating characters.
6+
7+
Example 1:
8+
Input: s = "abcabcbb"
9+
Output: 3
10+
Explanation: The answer is "abc", with the length of 3.
11+
12+
Example 2:
13+
Input: s = "bbbbb"
14+
Output: 1
15+
Explanation: The answer is "b", with the length of 1.
16+
17+
Example 3:
18+
Input: s = "pwwkew"
19+
Output: 3
20+
Explanation: The answer is "wke", with the length of 3.
21+
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
22+
23+
Example 4:
24+
Input: s = ""
25+
Output: 0
26+
27+
Constraints:
28+
0 <= s.length <= 5 * 104
29+
s consists of English letters, digits, symbols and spaces.
30+
*/
31+
32+
class Solution
33+
{
34+
public:
35+
int lengthOfLongestSubstring(string s)
36+
{
37+
int i = 0, j = 0;
38+
int n = s.size(), ans = 0;
39+
40+
vector<int> freq(256, 0);
41+
while (i < n && j < n)
42+
{
43+
while (freq[s[j]] > 0)
44+
{
45+
freq[s[i]]--;
46+
i++;
47+
}
48+
freq[s[j]]++;
49+
j++;
50+
ans = max(ans, j - i);
51+
}
52+
53+
return ans;
54+
}
55+
};

Striver Sheet/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
- [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/) - [Cpp Soultion](./Day-4/Longest%20Consecutive%20Sequence.cpp)
3737
- [Largest subarray with 0 sum](https://practice.geeksforgeeks.org/problems/largest-subarray-with-0-sum/1#) - [Cpp Soultion](./Day-4/Largest%20subarray%20with%200%20sum.cpp)
3838
- []() - [Cpp Soultion](./Day-4/.cpp)
39-
- []() - [Cpp Soultion](./Day-4/.cpp)
39+
- [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) - [Cpp Soultion](./Day-4/Longest%20Substring%20Without%20Repeating%20Characters.cpp)
4040

4141
###
4242

0 commit comments

Comments
 (0)