标签:targe app pen map stringbu i++ tar -- record
1 //从右往左 先排序一下 然后右到左进行替换 这样替换位置之前的index不会变 2 //注意一下Comparator的写法 3 class Solution { 4 public String findReplaceString(String S, int[] indexes, String[] sources, String[] targets) { 5 if(indexes.length == 0) return S; 6 StringBuilder sb = new StringBuilder(S); 7 int[][] record = new int[indexes.length][2]; 8 for(int i = 0; i < indexes.length; i++) { 9 record[i][0] = indexes[i]; 10 record[i][1] = i; 11 } 12 Arrays.sort(record, new Comparator<int[]>(){ 13 @Override 14 public int compare(int[] a, int[] b) { 15 return a[0]-b[0]; 16 } 17 }); 18 19 for(int i = record.length - 1; i >= 0; i--) { 20 if(S.indexOf(sources[record[i][1]], record[i][0]) == record[i][0]) { 21 sb.replace(record[i][0], record[i][0] + sources[record[i][1]].length(), targets[record[i][1]]); 22 } 23 24 } 25 26 27 return sb.toString(); 28 29 } 30 } 31 32 //HashMap 符合条件的位置和indexes的坐标i房间hashmap 然后一个位置一个位置从左向右加过去 33 class Solution { 34 public String findReplaceString(String S, int[] indexes, String[] sources, String[] targets) { 35 if(indexes.length == 0) return S; 36 StringBuilder sb = new StringBuilder(); 37 HashMap<Integer, Integer> map = new HashMap<>(); 38 for(int i = 0; i < indexes.length; i++) { 39 if(S.startsWith(sources[i], indexes[i])) { 40 map.put(indexes[i], i); 41 } 42 } 43 44 for(int i = 0; i < S.length(); i++) { 45 if(map.containsKey(i)) { 46 sb.append(targets[map.get(i)]); 47 i = i + sources[map.get(i)].length() - 1; 48 }else { 49 sb.append(S.charAt(i)); 50 } 51 } 52 return sb.toString(); 53 54 } 55 }
833. Find And Replace in String
标签:targe app pen map stringbu i++ tar -- record
原文地址:https://www.cnblogs.com/goPanama/p/9803374.html