Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
Example 1:
Input: s = "bcabc"
Output: "abc"
Example 2:
Input: s = "cbacdcbc"
Output: "acdb"
Constraints:
1 <= s.length <= 104sconsists of lowercase English letters.
Note: This question is the same as 1081: leetcode.com/problems/sm…
答案
func removeDuplicateLetters(s string) string {
fnt := [26]int{}
stack := make([]rune,0)
//记录字符是否已在栈中
seen := [26]bool{}
//统计出现频率
for _, e := range s {
fnt[e-'a']++
}
for _, e := range s {
index := e-'a'
//减去频率(记录后面该字符是否还会出现)
fnt[index]--
//该字符已在栈中存在
if seen[index] {
continue
}
for len(stack) > 0 {
peek := stack[len(stack)-1]
//要注意判断该字符在后面还会出现才能出栈
if peek > e && fnt[peek-'a'] != 0{
stack = stack[:len(stack)-1]
seen[peek-'a'] = false
}else {
break
}
}
stack = append(stack,e)
seen[e-'a'] = true
}
return string(stack)
}