-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsliding_windows.cpp
40 lines (38 loc) · 990 Bytes
/
sliding_windows.cpp
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 <iostream>
#include <vector>
#include <set>
#include <string>
using namespace std;
// 1.Longest Substring Without Repeating Characters
//sliding window O(n2)
int lengthOfLongestSubstring(string s) {
int left = 0, maxlen = 0, len = 0;
set<char> chset;
if(s=="")return 0;
for(int i=0; i<s.length();i++ ){
len = i-left+1;
for(int j = left; j<i; j++){
if (s[i] == s[j]){
len = i-j;
left = j+1;
}
}
if(len>maxlen)maxlen=len;
}
return maxlen;
}
//hashmap sliding windows O(n)
int lengthOfLongestSubstring(string s) {
int left = 0, maxlen = 0, len = 0;
map<char, int> mp;
if(s=="")return 0;
for(int i=0; i<s.length();i++ ){
if(mp.find(s[i])!=mp.end()){
left = max(mp[s[i]],left);
mp[s[i]] = i+1;
}else mp[s[i]] = i+1;
len = i-left+1;
if(len>maxlen)maxlen=len;
}
return maxlen;
}