very efficient method and the intuitive is great. Such problem is hard to explain by math. Here is my python version to implement above method.

class Solution(object):
def removeDuplicateLetters(self, s):
"""
:type s: str
:rtype: str
"""
size, cur, j = 0, 0, 0
char_count = [0 for i in range(26)]
visited = [False for i in range(26)]
t = ['0' for i in range(27)]
for ele in s : char_count[ord(ele) - 97] += 1
for ele in s :
cur = ord(ele) - 97
char_count[ cur ] -= 1
if visited[ cur ] : continue
j = size - 1
while j >= 0 :
if ele > t[j] or not char_count[ ord(t[j]) - 97] : break
else : visited[ord(t[j]) - 97] = False
j -= 1
j += 1
t[j] = ele
visited[cur] = True
size = j + 1
ret = ''
for i in range(size) : ret += t[i]
return ret