###### Middle-题目98：316. Remove Duplicate Letters

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.

Example:
Given “bcabc”
Return “abc”

Given “cbacdcbc”
Return “acdb”

public class Solution {
public String removeDuplicateLetters(String s) {
/**
* First loop: use an array cnt[] to count the number of times
* appeared for each letter in s.
*
* Second loop (Greedy): use a stack, pop() while (!stack.isEmpty()
* && (sc = stack.peek()) >= c && cnt[sc] > 0)
*/

int i, n = s.length();
int[] cnt = new int[128];
boolean[] inRes = new boolean[128]; // whether a char is in res[]
char[] res = s.toCharArray(); // simulate a stack

for (i = 0; i < n; i++)
cnt[res[i]]++;

char c, sc;
int end = -1;
// now cnt[c] means the remaining count of the char c
for (i = 0; i < n; i++) {
c = res[i];
if (inRes[c]) {
cnt[c]--;
continue;
}

while (end >= 0 && (sc = res[end]) >= c && cnt[sc] > 0) {
end--;
inRes[sc] = false;
}

res[++end] = c;
cnt[c]--;
inRes[c] = true;
}
return String.valueOf(res).substring(0, end + 1);
}
}

3ms,beats 95.32%，众数7ms,9.99%
cmershen的碎碎念：

public class Solution {
public String removeDuplicateLetters(String s) {
int[] cnt = new int[26];
int pos = 0; // the position for the smallest s[i]
for (int i = 0; i < s.length(); i++) cnt[s.charAt(i) - 'a']++;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) < s.charAt(pos)) pos = i;
if (--cnt[s.charAt(i) - 'a'] == 0) break;
}
return s.length() == 0 ? "" : s.charAt(pos) + removeDuplicateLetters(s.substring(pos + 1).replaceAll("" + s.charAt(pos), ""));
}
}

#### leetcode ：316 Remove Duplicate Letters ： 贪心+递归搜索

2016-03-28 23:20:28

#### [LeetCode 316] Remove Duplicate Letters

2015-12-28 16:57:02

#### leetcode316: Remove Duplicate Letters 使用递归的简单java实现

2015-12-28 22:58:08

#### leetcode_c++：栈：Remove Duplicate Letters（316 )

2016-07-23 15:42:20

#### leetcode -- Remove Duplicate Letters -- 还没完全理解。重点

2015-12-11 10:59:25

#### LeetCode 316. Remove Duplicate Letters（删除重复字母）

2016-04-23 05:51:58

#### leetcode 316. Remove Duplicate Letters 去除重复字符字典序最小字符串+贪心+递归

2017-10-02 11:03:03

#### [leetcode-316]Remove Duplicate Letters

2015-12-15 13:08:31

#### [leetcode] 316. Remove Duplicate Letters 解题报告

2016-05-06 06:19:43

#### 316. Remove Duplicate Letters

2016-04-09 22:46:02

## 不良信息举报

Middle-题目98：316. Remove Duplicate Letters