-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongest_substring_without_repeatition.cpp
More file actions
40 lines (36 loc) · 1.26 KB
/
longest_substring_without_repeatition.cpp
File metadata and controls
40 lines (36 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <bits/stdc++.h>
using namespace std;
int main()
{
string input_string = "pwwkew"; // input string
int n = input_string.size(); // size of string (given)
unordered_map<char, int> mp; // map data structure to keep track of unique characters
int max_window_size = INT_MIN; // max window varible to keep track of longest window size
int i, j; // pointers to mark end and start of window
i = j = 0; // intital value of pointers
// Sliding window Loop
while (j < n)
{
mp[input_string[j]]++; // increase the frequency of each element
if (mp[input_string[j]] <= 1)
{
max_window_size = max(max_window_size, j - i + 1); // compare between the length previous and present
j++;
}
else if (mp[input_string[j]] > 1)
{
while (mp[input_string[j]] > 1)
{
mp[input_string[i]]--;
if (mp[input_string[i]] == 0)
mp.erase(input_string[i]);
i++;
if (mp[input_string[j]] <= 1)
max_window_size = max(max_window_size, j - i + 1);
}
j++;
}
}
cout << max_window_size;
return 0;
}