The problem is an algorithmic question on the two side of the Pea pod, similar to some of the Leetcode's topics. The idea is this.
- First, iterate through the string to find out the number of different characters in the string
- Save a list for each character, and record the index of the character that appears in the string
- Records the first letter of the string to be evaluated start (initial value is 0), ending index end (initial value is length-1)
- The index value of the first letter of the possible string to be recorded is Pstart (the initial value is 0)
- Re-iterate the string with the current index
- Updates the number of characters that are not traversed, updating the list of indexes corresponding to the current character. If the Pstart character corresponds to a list length greater than 1, remove Pstart from the index list and add the Pstart to 1 and repeat the process
- If the character at index is the first occurrence, the number of remaining characters is reduced by one
- Update [start:end] to [Pstart:index] if the number of characters remaining is 0 o'clock and the substring [pstart:index] is shorter than [start:end]
return substring [start:end
You will find [Start:end] for the string to be asked. You can draw on the paper.
class solution {String Getshortestsubstring (StringStr) {if(Str==NULL||Str. Length () <=1) {return Str; }//Record the starting index of the target string intStart =0, end =Str. Length ()-1;//Record The starting position of the target string intPstart =0; Map<character, list<integer>> map =NewHashmap<character, list<integer>> (); for(int Index=0;Index<Str. Length ();Index+ +) {Map.put (Str. CharAt (Index),NULL); }intRemainingcharacter = Map.keyset (). Size (); for(inti =0; I <Str. Length (); i++) {Charc =Str. charAt (i);if(Map.get (c) = =NULL) {List List =NewLinkedlist<integer> (); Map.put (c, list); remainingcharacter--; } map.get (c). Add (i); while(Map.get (Str. CharAt (Pstart)). Size () >1) {Map.get (Str. CharAt (Pstart)). Remove (0); pstart++; }if(Remainingcharacter = =0) {if(I-pstart < End-start) {start = Pstart; end = i; } } }return Str. substring (start, end +1); }} class testsolution {@Test Public voidTestgetshortestsubstring () {Solution solution =NewSolution (); Assert.assertequals ("DBCCAAABCEFG", Solution.getshortestsubstring ("ABCDDBCCAAABCEFGGF")); }}
Given a string, find the shortest substring containing all the characters of the string