1 //sort from right to left and then right to left to replace so that the index does not change before the position is replaced2 //pay attention to the comparator.3 classSolution {4 PublicString findreplacestring (String S,int[] indexes, string[] sources, string[] targets) {5 if(Indexes.length = = 0)returnS;6StringBuilder SB =NewStringBuilder (S);7 int[] record =New int[Indexes.length] [2];8 for(inti = 0; i < indexes.length; i++) {9Record[i][0] =Indexes[i];TenRECORD[I][1] =i; One } AArrays.sort (Record,Newcomparator<int[]>(){ - @Override - Public intCompareint[] A,int[] b) { the returnA[0]-b[0]; - } - }); - + for(inti = record.length-1; I >= 0; i--) { - if(S.indexof (sources[record[i][1]], record[i][0]) = = Record[i][0]) { +Sb.replace (Record[i][0], record[i][0] + sources[record[i][1]].length (), targets[record[i][1]]); A } at - } - - - returnsb.tostring (); - in } - } to + //HashMap match the position of the condition and the coordinates of the indexes I room HashMap then a position one position from left to right add past - classSolution { the PublicString findreplacestring (String S,int[] indexes, string[] sources, string[] targets) { * if(Indexes.length = = 0)returnS; $StringBuilder SB =NewStringBuilder ();Panax NotoginsengHashmap<integer, integer> map =NewHashmap<>(); - for(inti = 0; i < indexes.length; i++) { the if(S.startswith (Sources[i], indexes[i])) { + Map.put (Indexes[i], i); A } the } + - for(inti = 0; I < s.length (); i++) { $ if(Map.containskey (i)) { $ Sb.append (Targets[map.get (i)]); -i = i + sources[map.get (i)].length ()-1; -}Else { the Sb.append (S.charat (i)); - }Wuyi } the returnsb.tostring (); - Wu } -}
833. Find and Replace in String