题目信息

解题思路

代码

  class Solution:
	  def removeDuplicateLetters(self, s: str) -> str:
		  mono_stack = []
		  app_dict = {} # char : largest idx of that char
		  cur_set = set() # make sure not adding existed char
		  for i in range(len(s)):
			  app_dict[s[i]] = i
		  for i in range(len(s)):
			  # check if new added char already existed
			  if s[i] in cur_set:
				  continue
			  while mono_stack and s[i] < mono_stack[-1]:
				  # check if mono_stack[-1] appears later
				  if app_dict[mono_stack[-1]] >= i:
					  cur_set.remove(mono_stack[-1])
					  mono_stack.pop()
				  else:
					  break
			  mono_stack.append(s[i])
			  cur_set.add(s[i])
		  return "".join(mono_stack)
	  
	  ```