[AlgoExpert] Longest Substring Without Duplication

Longest Substring Without Duplication

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using namespace std;

string longestSubstringWithoutDuplication(string str) {
int pos = -1, len = -1, n = str.length(), counter = 0, l = 0, r = 0;
unordered_map<char, int> mp;
while(r < n) {
if(++mp[str[r++]] == 2) counter++;
while(counter) {
if(--mp[str[l++]] == 1) counter--;
}
if(len < (r - l)) {
len = r - l;
pos = l;
}
}
return str.substr(pos, len);
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/10/PS/AlgoExpert/longest-substring-without-duplication/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.