Python stack solution with explanation
The solution is exactly the same as for 316. Remove Duplicate Letters.\n\nSave the temporary result into a stack.\nThe stack properties:\n(1) stack can be split
The solution is exactly the same as for [316. Remove Duplicate Letters.](https://leetcode.com/problems/remove-duplicate-letters/discuss/308977/Python-stack-solution-with-explanation)\n\nSave the temporary result into a stack.\nThe stack properties:\n(1) stack can be splitted to several segments\n(2) for each segment, the characters are lexicographically increasing\n(3) except the last segment, the last character doesn\'t appear in the future\n\n```\n    def smallestSubsequence(self, text: str) -> str:\n        rindex = {c: i for i, c in enumerate(text)}\n        stack = []\n        for i, c in enumerate(text):\n            if c not in stack:\n                while stack and c < stack[-1] and i < rindex[stack[-1]]:\n                    stack.pop()\n                stack.append(c)\n\t\t\t# else: c exists in stack\n\t\t\t# if stack[-1] == c: don\'t need to need to delete stack[-1] and append c\n\t\t\t# if stack[j] == c and j < len(stack) - 1: because of the stack properties, \n\t\t\t# the stack is lexicographically smaller than the new one after deleting stack[j] and appending c\n        return \'\'.join(stack)\n```\n\n```\n    def smallestSubsequence(self, text: str) -> str:\n        count, used = 26 * [0], 26 * [0]\n        for c in text:\n            count[ord(c) - ord(\'a\')] += 1\n        stack = []\n        for c in text:\n            count[ord(c) - ord(\'a\')] -= 1\n            if used[ord(c) - ord(\'a\')] == 0:\n                while stack and c < stack[-1] and count[ord(stack[-1]) - ord(\'a\')]:\n                    used[ord(stack[-1]) - ord(\'a\')] = 0\n                    stack.pop()\n                stack.append(c)\n                used[ord(c) - ord(\'a\')] = 1\n        return \'\'.join(stack)\n```
[]