Find And Replace in String
Apply several find-and-replace operations to a string at once, each checked against the original string.
Given a string sindicessourcestargetssources[i]sindices[i]targets[i]
All operations are checked against the original s
Example 1
Output: "eeebffff"
Example 2
Output: "eeecd"
Explanation: "ec" does not appear at position 2, so that operation does nothing.
The Idea
You have probably used find and replace in a text editor: you type a word, type what should go in its place, and the editor swaps them. Here there are several replacements at once, and each one names the exact position where its word must start.
In Example 1, s
The obvious plan is to apply operation 0 to the string, then operation 1 to what comes out. Does that work? Look at the picture below.
In the row labelled "one by one", operation 0 has already turned "a" into "eee". The string is now "eeebcd", two characters longer, and everything after the replacement has moved two places to the right. Position 2 now holds an e, so operation 1 no longer finds "cd", and the result stays "eeebcd", which is wrong.
The positions in indices
Solution Approach
Turning that idea into code means settling three things: which operations match, which operation starts at each position, and how the new string is built. Replacing from right to left, an alternative order, comes last.
Checking which operations match
How do we check one operation against the original? s.startsWith(sources[i], indices[i])sindices[i]sources[i]ss
Finding the operation at each position
The operations do not have to come in order of position: Example 1 could just as well list the "cd" operation first. So how does a left-to-right walk know which operation, if any, starts where it stands?
Keep an array opsop[p]op
Building the new string
What does the walk do at each position? A StringBuilderiop[i]iii
Replacing from right to left (optional)
Is there a way to keep the one-by-one plan? Yes, if the order changes: sort the operations by position, largest first, and replace starting from the right end. A replacement only moves the characters after it, and every operation still to come sits further left, so its position is still correct. It needs a sort, though, and each replacement on a Java String
Java Solution
The method findReplaceString
- First, create the array
, one entry per character ofop , and set every entry to -1 withs .Arrays.fill(op, -1) - Loop over the operations with
. Whenk is true, stores.startsWith(sources[k], indices[k]) ink .op[indices[k]] - Create a
namedStringBuilder for the result, and start the markersb at 0.i - While
is insidei , look ats . If it holds an operation, appendop[i] totargets[op[i]] and add the length ofsb tosources[op[i]] . Otherwise appendi and moves.charAt(i) one step.i - When
reaches the end ofi , returns .sb.toString()
The main
import java.util.Arrays;
public class FindAndReplaceInString {
public static String findReplaceString(String s, int[] indices, String[] sources,
String[] targets) {
int[] op = new int[s.length()]; // op[p]: which operation replaces at p, or -1
Arrays.fill(op, -1);
for (int k = 0; k < indices.length; k++) {
if (s.startsWith(sources[k], indices[k])) {
op[indices[k]] = k; // checked against the ORIGINAL string
}
}
StringBuilder sb = new StringBuilder();
int i = 0;
while (i < s.length()) {
if (op[i] >= 0) {
sb.append(targets[op[i]]);
i += sources[op[i]].length(); // skip the replaced part
} else {
sb.append(s.charAt(i++));
}
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(findReplaceString("abcd", new int[] {0, 2},
new String[] {"a", "cd"}, new String[] {"eee", "ffff"}));
System.out.println(findReplaceString("abcd", new int[] {0, 2},
new String[] {"ab", "ec"}, new String[] {"eee", "ffff"}));
System.out.println(findReplaceString("abcd", new int[] {2, 0},
new String[] {"cd", "a"}, new String[] {"ffff", "eee"}));
System.out.println(findReplaceString("abc", new int[] {2},
new String[] {"cde"}, new String[] {"x"}));
System.out.println(findReplaceString("a-b-c", new int[] {3, 1},
new String[] {"-", "-"}, new String[] {"", ""}));
}
}
Running it prints:
eeebffff
eeecd
eeebffff
abc
abc
The first line, eeebffffeeecd
Look at the third line: eeebffffop
The fourth line is "abc", unchanged. "cde" would need positions 2 to 4, but "abc" has only three characters, and startsWith
Complexity
The work is one check per operation, plus one walk over ss
- Time: O(n + L), because filling
touches each of the n positions once, eachop compares at most the characters of one source, and the walk appends each kept character and each used target once.startsWith - Space: O(n) besides the result, for the
array with its one entry per position ofop . Thes holds the result itself, whose length depends on the targets.StringBuilder
Building a string piece by piece with a StringBuilder