From ae73cbe6b8e02dd01f6de59ebadd6e64d6764147 Mon Sep 17 00:00:00 2001 From: juan Date: Thu, 14 Jul 2022 10:02:54 +0800 Subject: [PATCH] vault backup: 2022-07-14 10:02:54 --- ...-Substring-Without-Repeating-Characters.md | 47 ++++++++++++++++--- OJ notes/pages/Leetcode.md | 0 2 files changed, 41 insertions(+), 6 deletions(-) create mode 100644 OJ notes/pages/Leetcode.md diff --git a/OJ notes/pages/Leetcode Longest-Substring-Without-Repeating-Characters.md b/OJ notes/pages/Leetcode Longest-Substring-Without-Repeating-Characters.md index a912520..07d7190 100644 --- a/OJ notes/pages/Leetcode Longest-Substring-Without-Repeating-Characters.md +++ b/OJ notes/pages/Leetcode Longest-Substring-Without-Repeating-Characters.md @@ -3,7 +3,7 @@ #### 2022-07-14 09:33 > ##### Algorithms: -> #algorithm +> #algorithm #Kadane_s_algorithm > ##### Data structures: > #DS #string > ##### Difficulty: @@ -15,10 +15,12 @@ ##### Related topics: ```expander -tag:# +tag:#Kadane_s_algorithm ``` - - + + + + ##### Links: - [Link to problem](https://leetcode.com/problems/longest-substring-without-repeating-characters/) @@ -56,12 +58,45 @@ Notice that the answer must be a substring, "pwke" is a subsequence and not a su ### Thoughts > [!summary] -> This is a # +> This is a #Kadane_s_algorithm -Initially, I thought of a lineal algorithm +Initially, I thought of a kadane's algo, but implemented wrong. + +Then I figured out kadane's algorithm. + +similar to this one. +[[Leetcode Best-Time-To-Buy-And-Sell-Stock]] + +The goal is making cur as small as possible, without duplicating ### Solution +Kadane's algorithm + +```cpp +class Solution { +public: + int lengthOfLongestSubstring(string s) { + // Kadane's algorithm + vector hMap(255, -1); + + int cur = -1; + int localMax = 0; + + for (int i = 0; i < s.length(); i++) { + if (hMap[s[i]] > cur) { + // If the element occurs again, reset + cur = hMap[s[i]]; + } + + hMap[s[i]] = i; + localMax = max(localMax, i - cur); + } + return localMax; + } +}; +``` + Initial solution ```cpp diff --git a/OJ notes/pages/Leetcode.md b/OJ notes/pages/Leetcode.md new file mode 100644 index 0000000..e69de29