题目较长,主要是遍历长度为
k
k
k的数组并完成替换,其例子如下:
即找到原数组从
s
[
i
n
d
i
c
e
s
[
i
]
]
s[indices[i]]
s[indices[i]] 开始与数组
s
o
u
r
e
s
[
i
]
soures[i]
soures[i]进行匹配,若存在相同字符串项,则使用
t
a
r
g
e
t
[
i
]
target[i]
target[i] 来进行替换。
题中提出了保证测试数据不会出现重叠冲突,因此思路就是常规进行匹配然后替换。
关键问题:
主要是如何满足同时替换的问题,如上图中所示,在替换时字符串的长度发生了变化,因此若按照索引进行替换时会出错。
我采用
l
i
s
t
list
list 来储存原字符串
s
s
s 中需要替换的元素的下标以及需要替换的长度,由于不会产生冲突,且无法知道
i
n
d
i
c
e
s
indices
indices 是否进行了排序,因此在得到
l
i
s
t
list
list 之后对元素进行排序。
如上图中所示,
l
i
s
t
list
list 储存字符串
s
s
s 中的需要替换的下标,
m
a
p
map
map 根据键值对储存需要替换的下标以及替换的字符串。
采用 S t r i n g B u f f e r StringBuffer StringBuffer 来新建对象,遍历 s s s 同时进行替换,即可得到同步替换的结果。代码如下:
class Solution {
public String findReplaceString(String s, int[] indices, String[] sources, String[] targets) {
List<int[]> list = new ArrayList<>();
Map<Integer,String> map = new HashMap<>();
for(int i=0 ; i<sources.length ; i++){
String subString = s.substring(indices[i]);
if(compare(subString,sources[i])){
list.add(new int[]{indices[i],indices[i]+sources[i].length()});
map.put(indices[i],targets[i]);
}
}
list.sort((a,b)->(a[0]-b[0]));
StringBuffer sb = new StringBuffer();
int i = 0, j = 0;
while (i<s.length()){
if(j>=list.size()){
sb.append(s.charAt(i));
i++;
continue;
}
if(i<list.get(j)[0]){
sb.append(s.charAt(i));
i++;
continue;
}
if(i==list.get(j)[0]){
sb.append(map.get(list.get(j)[0]));
i+=list.get(j)[1]-list.get(j)[0];
j++;
}
}
return sb.toString();
}
public boolean compare(String s1,String s2){
int i = 0;
while (i < s2.length()){
if(i >= s1.length()) return false;
if(s1.charAt(i) != s2.charAt(i)) return false;
i++;
}
return true;
}
}