LeetCode Problem
833. Find And Replace in String
Link to LeetCode
To some string S, we will perform some replacement operations that replace groups of letters with new ones (not necessarily the same size).
Each replacement operation has 3 parameters: a starting index i, a source word x and a target word y. The rule is that if x starts at position i in the original string S, then we will replace that occurrence of x with y. If not, we do nothing.
Example :
Input: s = "abcd", indices = [0, 2], sources = ["a", "cd"], targets = ["eee", "ffff"]
Output: "eeebffff"
Explanation:
"a" occurs at index 0 in s, so we replace it with "eee".
"cd" occurs at index 2 in s, so we replace it with "ffff".
class Solution {
public String findReplaceString(String s, int[] indexes, String[] sources, String[] targets) {
Map< Integer, String[]> inputMap = new HashMap<>();
for (int i=0; i< indexes.length; i++) {
inputMap.put(indexes[i], new String[]{sources[i], targets[i]});
}
Map< Integer, String> tempMap = new LinkedHashMap<>();
int i=0;
while (i< s.length()) {
String[] value = inputMap.get(i);
if (value != null && isValid (s, i, value[0])) {
tempMap.put(i, value[1]);
i += value[0].length();
} else {
tempMap.put(i, "" + s.charAt(i));
i++;
}
}
StringBuilder sb = new StringBuilder();
for (Map.Entry< Integer, String> entry : tempMap.entrySet()) {
sb.append(entry.getValue());
}
return sb.toString();
}
private boolean isValid(String s, int index, String sub) {
int j=0;
for (int i=index; i< s.length() && j< sub.length(); i++, j++) {
if (s.charAt(i)!=sub.charAt(j)) {
return false;
}
}
return j == sub.length();
}
}