Skip to content

Commit

Permalink
三刷3
Browse files Browse the repository at this point in the history
  • Loading branch information
diguage committed Sep 21, 2024
1 parent dd7c814 commit 84ad012
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
20 changes: 20 additions & 0 deletions docs/0003-longest-substring-without-repeating-characters.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -62,15 +62,35 @@ image::images/0003-09.png[{image_attr}]
image::images/0003-10.png[{image_attr}]

[[src-0003]]
[tabs]
====
一刷::
+
--
[{java_src_attr}]
----
include::{sourcedir}/_0003_LongestSubstringWithoutRepeatingCharacters.java[tag=answer]
----
--
二刷::
+
--
[{java_src_attr}]
----
include::{sourcedir}/_0003_LongestSubstringWithoutRepeatingCharacters_2.java[tag=answer]
----
--
三刷::
+
--
[{java_src_attr}]
----
include::{sourcedir}/_0003_LongestSubstringWithoutRepeatingCharacters_3.java[tag=answer]
----
--
====

== 参考资料

Expand Down
4 changes: 4 additions & 0 deletions logbook/202406.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -833,6 +833,10 @@
|{doc_base_url}/0400-nth-digit.adoc[题解]
|❌ 纯纯的数学运算,一脸懵逼

|{counter:codes}
|{leetcode_base_url}/longest-substring-without-repeating-characters/[3. Longest Substring Without Repeating Characters^]
|{doc_base_url}/0003-longest-substring-without-repeating-characters.adoc[题解]
|✅ 滑动窗口。滑动窗口的模板不是很熟悉。可以不存字符格式,存字符最大的坐标。

|===

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.diguage.algo.leetcode;

import java.util.HashMap;
import java.util.Map;

public class _0003_LongestSubstringWithoutRepeatingCharacters_3 {
// tag::answer[]

/**
* @author D瓜哥 · https://www.diguage.com
* @since 2024-07-02 19:27:43
*/
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> map = new HashMap<>();
int result = 0, left = 0;
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
int cnt = map.getOrDefault(c, 0);
if (cnt == 0) {
map.put(c, 1);
result = Math.max(result, right - left + 1);
} else {
map.put(c, cnt + 1);
}
while (map.get(c) > 1) {
char lc = s.charAt(left);
left++;
map.put(lc, map.get(lc) - 1);
}
}
return result;
}
// end::answer[]
}

0 comments on commit 84ad012

Please sign in to comment.