Skip to content

Commit 6f566aa

Browse files
committed
三刷316
1 parent cc3d684 commit 6f566aa

File tree

3 files changed

+53
-1
lines changed

3 files changed

+53
-1
lines changed

docs/0316-remove-duplicate-letters.adoc

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
[#0316-remove-duplicate-letters]
22
= 316. 去除重复字母
33

4-
https://leetcode.cn/problems/remove-duplicate-letters/[LeetCode - 316. 去除重复字母 ^]
4+
https://leetcode.cn/problems/remove-duplicate-letters/[LeetCode - 316. 去除重复字母^]
55

66
给你一个字符串 `s`,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证 *返回结果的字典序最小*(要求不能打乱其他字符的相对位置)。
77

@@ -50,6 +50,15 @@ include::{sourcedir}/_0316_RemoveDuplicateLetters.java[tag=answer]
5050
include::{sourcedir}/_0316_RemoveDuplicateLetters_2.java[tag=answer]
5151
----
5252
--
53+
54+
三刷::
55+
+
56+
--
57+
[{java_src_attr}]
58+
----
59+
include::{sourcedir}/_0316_RemoveDuplicateLetters_3.java[tag=answer]
60+
----
61+
--
5362
====
5463

5564

logbook/202503.adoc

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1509,6 +1509,11 @@ endif::[]
15091509
|{doc_base_url}/0003-longest-substring-without-repeating-characters.adoc[题解]
15101510
|✅ 复习 {doc_base_url}/0000-09-sliding-window.adoc[Sliding Window 滑动窗口]。我采用的是计数法,也可以采用地址法。
15111511

1512+
|{counter:codes2503}
1513+
|{leetcode_base_url}/remove-duplicate-letters/[316. 去除重复字母^]
1514+
|{doc_base_url}/0316-remove-duplicate-letters.adoc[题解]
1515+
|❌ 复习 {doc_base_url}/0000-10-monotonic-stack.adoc[Monotonic Stack 单调栈]。知道是单调栈,代码还是没写出来!看到题解,又里面秒懂。
1516+
15121517
|===
15131518

15141519
截止目前,本轮练习一共完成 {codes2503} 道题。
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package com.diguage.algo.leetcode;
2+
3+
public class _0316_RemoveDuplicateLetters_3 {
4+
// tag::answer[]
5+
6+
/**
7+
* @author D瓜哥 · https://www.diguage.com
8+
* @since 2025-09-11 21:13:45
9+
*/
10+
public String removeDuplicateLetters(String s) {
11+
char[] chars = s.toCharArray();
12+
int[] counter = new int[26];
13+
for (char c : chars) {
14+
counter[c - 'a']++;
15+
}
16+
boolean[] added = new boolean[26];
17+
StringBuilder result = new StringBuilder();
18+
for (char c : chars) {
19+
int idx = c - 'a';
20+
counter[c - 'a']--;
21+
if (added[idx]) {
22+
continue;
23+
}
24+
while (!result.isEmpty() && result.charAt(result.length() - 1) > c) {
25+
int lastIdx = result.charAt(result.length() - 1) - 'a';
26+
if (counter[lastIdx] == 0) {
27+
break;
28+
}
29+
result.deleteCharAt(result.length() - 1);
30+
added[lastIdx] = false;
31+
}
32+
result.append(c);
33+
added[idx] = true;
34+
}
35+
return result.toString();
36+
}
37+
// end::answer[]
38+
}

0 commit comments

Comments
 (0)