Skip to content

Commit 551e536

Browse files
committed
finish 316
1 parent a06b91c commit 551e536

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# 316. Remove Duplicate Letters
2+
3+
- Difficulty: Hard.
4+
- Related Topics: Stack, Greedy.
5+
- Similar Questions: .
6+
7+
## Problem
8+
9+
Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
10+
11+
**Example 1:**
12+
13+
```
14+
Input: "bcabc"
15+
Output: "abc"
16+
```
17+
18+
**Example 2:**
19+
20+
```
21+
Input: "cbacdcbc"
22+
Output: "acdb"
23+
```
24+
25+
## Solution
26+
27+
```javascript
28+
/**
29+
* @param {string} s
30+
* @return {string}
31+
*/
32+
var removeDuplicateLetters = function(s) {
33+
var count = {};
34+
var len = s.length;
35+
var index = 0;
36+
37+
if (!len) return '';
38+
39+
for (var i = 0; i < len; i++) {
40+
if (count[s[i]] === undefined) count[s[i]] = 0;
41+
count[s[i]]++;
42+
}
43+
44+
for (var j = 0; j < len; j++) {
45+
if (s[j] < s[index]) index = j;
46+
if (--count[s[j]] === 0) break;
47+
}
48+
49+
var firstChar = s[index];
50+
var restString = s.substr(index + 1);
51+
52+
restString = restString.replace(new RegExp(firstChar, 'g'), '');
53+
54+
return firstChar + removeDuplicateLetters(restString);
55+
};
56+
```
57+
58+
**Explain:**
59+
60+
贪心,每次找到排第一的字符,再递归。
61+
62+
**Complexity:**
63+
64+
* Time complexity : O(n).
65+
* Space complexity : O(n).

0 commit comments

Comments
 (0)