833. 字符串中的查找与替换
对于某些字符串
S
,我们将执行一些替换操作,用新的字母组替换原有的字母组(不一定大小相同)。每个替换操作具有 3 个参数:起始索引
i
,源字x
和目标字y
。规则是如果x
从原始字符串S
中的位置i
开始,那么我们将用y
替换出现的x
。如果没有,我们什么都不做。举个例子,如果我们有
S = “abcd”
并且我们有一些替换操作i = 2,x = “cd”,y = “ffff”
,那么因为“cd”
从原始字符串S
中的位置2
开始,我们将用“ffff”
替换它。再来看
S = “abcd”
上的另一个例子,如果我们有替换操作i = 0,x = “ab”,y = “eee”
,以及另一个替换操作i = 2,x = “ec”,y = “ffff”
,那么第二个操作将不执行任何操作,因为原始字符串中S[2] = 'c'
,与x[0] = 'e'
不匹配。所有这些操作同时发生。保证在替换时不会有任何重叠:
S = "abc", indexes = [0, 1], sources = ["ab","bc"]
不是有效的测试用例。思路:对indexes进行排序,保证sources和targets数组中的字符串相对位置边,然后从后往前替换
class Node implements Comparable<Node>{
String source;
String target;
int index;
public Node(int index,String source,String target) {
// TODO Auto-generated constructor stub
this.index = index;
this.source = source;
this.target = target;
}
@Override
public int compareTo(Node o) {
// TODO Auto-generated method stub
return o.index - this.index;
}
}
public String findReplaceString(String S, int[] indexes, String[] sources, String[] targets) {
PriorityQueue<Node> pQueue = new PriorityQueue<Node>();
for(int i = 0;i < indexes.length;i++) {
Node node = new Node(indexes[i],sources[i],targets[i]);
pQueue.add(node);
}
StringBuilder sb = new StringBuilder(S);
while (!pQueue.isEmpty()) {
Node node = pQueue.poll();
if(S.startsWith(node.source,node.index)) {
sb.delete(node.index, node.index + node.source.length());
sb.insert(node.index, node.target);
}
}
return sb.toString();
}