Remove Duplicate Letters Leetcode python
Remove Duplicate Letters
Runtime: 272 mshttps://leetcode.com/problems/remove-duplicate-letters/
Greedy solution, recursive,
1. Loop the string to find the letter(and it's position) which does not have duplicate or it's smallest among all letter in the string; if there are multiple of the smallest letter, use the position of the leftmost one
2. call the function recursively, partition the string s[pos+1:], where pos is the one we find in step1, and replace all other occurence of the letter at s[pos]
from collections import Counter
class Solution(object):
def removeDuplicateLetters(self, s):
"""
:type s: str
:rtype: str
"""
# s = list(s)
if len(s) == 0:
return ""
d = Counter()
pos = 0
for i,c in enumerate(s):
d[c]+=1
for i,c in enumerate(s):
if c < s[pos]:
pos = i
if d[c] == 1:
break
d[c] -=1
return s[pos]+self.removeDuplicateLetters(s[pos+1:].replace(s[pos],""))
评论