833. Find and Replace in String

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.