title :
Given a string which contains only lowercase letters, remove duplicate letters so this every letter appear once and only O nCE. You must make sure your result are the smallest in lexicographical order among all possible results.
Example:
Given"bcabc"
Return"abc"
Given"cbacdcbc"
Return"acdb"
Problem Solving Ideas :
The idea of this problem is to delete all the repeated letters, the final sequence of the number of letters are unique, and try to keep the letter value of the small line in front.
You can iterate through the array and send all the letters and the index value it appears to the map.
"Bcabc", ' A ' and ' 2; ' B ' =>0,3; ' C ' =>1,4
First find the index of the smallest letter, the first is a, its index is 2, and then B,c, the outermost index3,4, are greater than 2.
Delete the letters before a, which will become a joy in the map, ' B ' = 3, ' C ' =>4
By analogy, you know that the size of the map is empty.
Java code :
28ms
Publicstring Removeduplicateletters (string s) {Map<character, list<integer>> map =NewHashmap<character, list<integer>>(); if(s = =NULL|| S.length () <=1)returns; intLen =s.length (); List<Character> keys =NewArraylist<character>(); for(inti = 0; i < Len; i++){ Charc =S.charat (i); List<Integer> list =NULL; if(Map.containskey (c)) {list=Map.get (c); }Else{List=NewArraylist<integer>(); Keys.add (c); } list.add (i); Map.put (c, list); } collections.sort (keys); StringBuilder SB=NewStringBuilder (); while(!Map.isempty ()) { BooleanFound =true; for(intj = 0; J < Keys.size (); J + +){ CharCur =Keys.get (j); intCurindex = Map.get (cur). Get (0); for(intn = 0; N < keys.size (); n++) {List<Integer> curlist =Map.get (Keys.get (n)); if(Curlist.get (Curlist.size ()-1) <Curindex) {Found=false; Break; } } if(found) {sb.append (cur); Map.Remove (cur); Keys.remove (j); for(intm = 0; M < Keys.size (); m++){ Chartemp =Keys.get (m); List<Integer> templist =Map.get (temp); Iterator<Integer> it =Templist.iterator (); while(It.hasnext ()) {Integer Val=It.next (); if(Val <Curindex) {It.remove (); } } } Break; } Found=true; } } returnsb.tostring (); }
[Leetcode]: Remove Duplicate Letters