LeetCode – Find And Replace in String (Java)

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.

For example, if we have S = “abcd” and we have some replacement operation i = 2, x = “cd”, y = “ffff”, then because “cd” starts at position 2 in the original string S, we will replace it with “ffff”.

Java Solution

public String findReplaceString(String S, int[] indexes, String[] sources, String[] targets) {
    StringBuilder sb = new StringBuilder();
    TreeMap<Integer, String[]> map = new TreeMap<>();
    for (int i = 0; i < indexes.length; i++) {
        map.put(indexes[i], new String[]{sources[i], targets[i]});
    }
 
    int prev = 0;
 
    for (Map.Entry<Integer, String[]> entry : map.entrySet()) {
        int startIndex = entry.getKey();
        int endIndex = startIndex + entry.getValue()[0].length();
 
        if (prev != startIndex) {
            sb.append(S.substring(prev, startIndex));
        }
 
        String org = S.substring(startIndex, endIndex);
        if (org.equals(entry.getValue()[0])) {
            sb.append(entry.getValue()[1]);
            prev = endIndex;
        } else {
            sb.append(org);
            prev = endIndex;
        }
 
    }
 
    if (prev < S.length()) {
        sb.append(S.substring(prev));
    }
 
    return sb.toString();
}

2 thoughts on “LeetCode – Find And Replace in String (Java)”

  1. The provided Java code implements a function called findReplaceString that performs replacement operations on a given input string S. These replacement operations are specified by arrays containing starting indexes, source words, and target words. The code constructs a modified string based on these operations and ensures that replacements occur in the correct order. Mulesoft Training


  2. class Solution {
    public:
    string findReplaceString(string S, vector& indexes, vector& sources, vector& targets) {
    unordered_map mp;
    for(int i = 0; i < indexes.size(); i++) mp[indexes[i]] = i;
    string ans = "";
    for(int i = 0; i = S.size()) {
    ans += S[i];
    }
    else {
    string part = S.substr(i, sources[mp[i]].size());
    if(part == sources[mp[i]]) {
    ans += targets[mp[i]];
    i += part.size() - 1;
    }
    else ans += S[i];
    }
    }
    return ans;
    }
    };

Leave a Comment