add: 220610 [cpp]
This commit is contained in:
parent
3cc6b0c5e2
commit
9ae05b0458
|
|
@ -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;
|
||||
}
|
||||
};
|
||||
|
|
@ -3,4 +3,4 @@ PROJECT(2206)
|
|||
|
||||
SET(CMAKE_CXX_STANDARD 23)
|
||||
|
||||
ADD_EXECUTABLE(2206 220611.cpp)
|
||||
ADD_EXECUTABLE(2206 220610.cpp)
|
||||
|
|
|
|||
Loading…
Reference in New Issue