From 9ae05b04581e5fcde9f07a1042ae21c502b984f4 Mon Sep 17 00:00:00 2001 From: Eat-Swap Date: Mon, 13 Jun 2022 23:24:48 +0800 Subject: [PATCH] add: 220610 [cpp] --- cpp/2206/220610.cpp | 43 +++++++++++++++++++++++++++++++++++++++++ cpp/2206/CMakeLists.txt | 2 +- 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 cpp/2206/220610.cpp diff --git a/cpp/2206/220610.cpp b/cpp/2206/220610.cpp new file mode 100644 index 0000000..d2d7016 --- /dev/null +++ b/cpp/2206/220610.cpp @@ -0,0 +1,43 @@ +#include +#include + +/** + * 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 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; + } +}; diff --git a/cpp/2206/CMakeLists.txt b/cpp/2206/CMakeLists.txt index a687c49..fff3106 100644 --- a/cpp/2206/CMakeLists.txt +++ b/cpp/2206/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2206) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2206 220611.cpp) +ADD_EXECUTABLE(2206 220610.cpp)