Skip to content

Commit a14bdf5

Browse files
committed
字符串去重, 字典序输出(栈)
1 parent 7305962 commit a14bdf5

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ leetcode刷题, 直接用leetcode的分类方式.
55
- 字符串
66
- [x] 链表 (完成时间: 2018-01-28)
77
- 哈希表
8-
- 堆栈
8+
- [x] 堆栈 (完成时间: 2018-02-07)
99
- 双指针
1010
- [x] 树 (完成时间: 2018-02-04)
1111
-

Stack/316_RemoveDuplicateLetters.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# coding: utf8
2+
3+
4+
"""
5+
题目链接: https://leetcode.com/problems/remove-duplicate-letters/description.
6+
题目描述:
7+
8+
Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and
9+
only once. You must make sure your result is the smallest in lexicographical order among all possible results.
10+
11+
Example:
12+
Given "bcabc"
13+
Return "abc"
14+
15+
Given "cbacdcbc"
16+
Return "acdb"
17+
18+
Credits:
19+
Special thanks to @dietpepsi for adding this problem and creating all test cases.
20+
21+
"""
22+
23+
24+
class Solution(object):
25+
def removeDuplicateLetters(self, s):
26+
"""
27+
:type s: str
28+
:rtype: str
29+
"""
30+
if not s or len(s) < 2:
31+
return s
32+
33+
vis = [0] * 26
34+
cnt = [0] * 26
35+
ans = []
36+
for c in s:
37+
cnt[ord(c) - 97] += 1
38+
# 遍历, 若当前字符已入栈, 跳过
39+
# 否则, 与栈顶字符比较, 若小于栈顶字符且cnt[c] > 0(证明后面还会出现该字符), 出栈, 同时访问标记置为0
40+
# 当前字符入栈, 访问标记置为1
41+
for c in s:
42+
idx = ord(c) - 97
43+
cnt[idx] -= 1
44+
if vis[idx]:
45+
continue
46+
while ans and c < ans[-1] and cnt[ord(ans[-1]) - 97]:
47+
vis[ord(ans[-1]) - 97] = 0
48+
ans.pop()
49+
ans.append(c)
50+
vis[idx] = 1
51+
52+
return ''.join(ans)

0 commit comments

Comments
 (0)