Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions 3_longest_substring_without_repeating_characters/memo.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# 3. Longest Substring Without Repeating Characters

https://leetcode.com/problems/longest-substring-without-repeating-characters/

## Comments

### step1

* Arai60 で解いた問題なのでさらっと
* https://github.com/ryosuketc/leetcode_arai60/pull/37/files
* 愚直に O(n^2) で探索もできるなあ、などと思いつつ、sliding window として解く
* 最初 `chars_in_substring.contains(s[right])` を if 文にしたうえで `while` の条件に使ってしまっていたりしたが書いている途中でさっと書き直した。
* 最初 `max_substring_length = s.size()` で初期化してしまっており WA になった。
* 9:00 くらいで AC。あまり前解いたときのことを覚えていなかったので思ったより時間かかった。

### step2

* step1 の弧ー0度はまあそれ自体は別にそれでいいかなという感じ。
* 強いて言えば for でなく while で書いたほうが left, right に対称性があってきれいかもしれない
* index 管理しておいて、left を一気に飛ばすやり方忘れていた。さっと書いてみる

### step3

* skip
19 changes: 19 additions & 0 deletions 3_longest_substring_without_repeating_characters/step1.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#include <unordered_set>

class Solution {
public:
int lengthOfLongestSubstring(string s) {
int left = 0;
std::unordered_set<char> chars_in_substring;
int max_substring_length = 0;
for (int right = 0; right < s.size(); ++right) {
while (chars_in_substring.contains(s[right])) {
chars_in_substring.erase(s[left]);
++left;
}
chars_in_substring.insert(s[right]);
max_substring_length = std::max(max_substring_length, right - left + 1);
}
return max_substring_length;
}
};
20 changes: 20 additions & 0 deletions 3_longest_substring_without_repeating_characters/step2.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#include <unordered_map>

class Solution {
public:
int lengthOfLongestSubstring(string s) {
int left = 0;
int right = 0;
int max_substring_length = 0;
std::unordered_map<char, int> seen_index;
while (right < s.size()) {
if (seen_index.contains(s[right])) {
left = std::max(left, seen_index[s[right]] + 1);
}
max_substring_length = std::max(max_substring_length, right - left + 1);
seen_index[s[right]] = right;
++right;
}
return max_substring_length;
}
};
Empty file.