add: 220610 [cpp]

This commit is contained in:
Eat-Swap 2022-06-13 23:24:48 +08:00
parent 3cc6b0c5e2
commit 9ae05b0458
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
2 changed files with 44 additions and 1 deletions

43
cpp/2206/220610.cpp Normal file
View File

@ -0,0 +1,43 @@
#include <unordered_set>
#include <string>
/**
* 3. Longest Substring Without Repeating Characters
* Given a string s, find the length of the longest substring without repeating characters.
*
* 100% same algorithm as -> 220612.cpp
*/
class Solution {
public:
static int lengthOfLongestSubstring(const std::string& str) {
std::unordered_set<int> s;
const int n = str.length();
int sum = 0, ret = 0;
for (int i = 0, l = 0; i < n; ++i) {
std::printf("In loop, i = %d, l = %d\nStart inserting: ", i, l);
for (; i < n && !s.count(str[i]); ++i) {
++sum; // sum += str[i];
s.insert(str[i]);
std::printf("%d ", str[i]);
}
ret = std::max(ret, sum);
if (i == n)
break;
std::printf("\nEnd inserting at position %d, str[i] = %d, updating ret <- %d\nStart popping: ", i, str[i], ret);
// pop until reach str[i]
for (; str[l] != str[i]; ++l) {
s.erase(str[l]);
--sum; // sum -= str[l];
std::printf("%d ", str[l]);
}
++l; // where str[l] == str[i]
std::printf("\nEnd loop, where i = %d, l = %d\n\n", i, l);
}
return ret;
}
};

View File

@ -3,4 +3,4 @@ PROJECT(2206)
SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2206 220611.cpp) ADD_EXECUTABLE(2206 220610.cpp)