@@ -0,0 +1,1601 @@
+/*%0A Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.%0A%0AExample:%0A%0AGiven %22bcabc%22%0AReturn %22abc%22%0A%0AGiven %22cbacdcbc%22%0AReturn %22acdb%22 %0A*/%0Aimport java.util.*;%0A%0Apublic class RemoveDuplicateLetters %7B%0A%09public static String removeDuplicateLetters(String s) %7B%0A        if(s.length() %3C= 0) return %22%22;%0A        int%5B%5D counts = new int%5B26%5D;%0A        for(int i = 0; i %3C s.length(); i++)%7B%0A            counts%5Bs.charAt(i) - 'a'%5D++;%0A        %7D%0A        int pos = 0;%0A        %0A        for(int i = 0; i %3C s.length(); i++)%7B%0A            if(s.charAt(i) %3C s.charAt(pos)) pos = i;%0A            if(--counts%5Bs.charAt(i) - 'a'%5D == 0) break;  // find the smallest letter from left to right until a letter reaches its last index%0A            // meaning it cannot be readd later, meaning the smallest letter must be added before the reach-last-index letter%0A            // but the reach-last-index letter cannot be added because there might be another letter smaller than it but before it.%0A        %7D%0A        if(s.length() == 0)%7B%0A            return %22%22;%0A        %7Delse%7B%0A            return s.charAt(pos) + removeDuplicateLetters(s.substring(pos+1).replaceAll(%22%22+s.charAt(pos), %22%22));%0A        %7D%0A        %0A    %7D%0A%09public static void main(String%5B%5D args) %7B%0A%09%09String s = %22cbacdcbc%22;%0A%09%09String res = removeDuplicateLetters(s);%0A%09%09System.out.println(%22String: %22 + s);%0A%09%09System.out.println(%22Remove duplicates, reserve the order with smallest order in dictionary: %22 + res);%0A%09%09return;%0A%09%7D%09%0A%7D%0A

remove duplicate letters, reserve the order, return the smallest order