833. Find And Replace in String

Posted gopanama

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了833. Find And Replace in String相关的知识,希望对你有一定的参考价值。

 

 

 

 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的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 833. Find And Replace in String

查找并替换字符串 Find And Replace in String

[LeetCode] Find And Replace in String 在字符串中查找和替换

Implement Find and replace (find given pattern and replace it with a given string)

890. Find and Replace Pattern

890. Find and Replace Pattern