classSolution{ public String smallestSubsequence(String s){ if (s == null || s.length() <= 1) return s; Stack<Character> st = new Stack<>(); int[] set = newint[128]; //record if stack has the character int[] map = newint[128]; //record the number of characters remaining for (char ch: s.toCharArray()){ map[ch]++; } for (char ch: s.toCharArray()){ if (set[ch] > 0) { map[ch]--; continue; } while (!st.isEmpty() && ch < st.peek() && map[st.peek()] > 0){ set[st.pop()] = 0; } st.push(ch); set[ch] = 1; map[ch]--; } StringBuilder res = new StringBuilder(); while(!st.isEmpty()) res.append(st.pop()); return res.reverse().toString(); } }