Gyh's Braindump

833. Find And Replace in String

tags
subarray
source
leetcode

Edge Cases

index array may not sorted

Solution

class Solution {
    public String findReplaceString(String S, int[] indexes, String[] sources, String[] targets) {
        StringBuilder sb = new StringBuilder();
        int[] match = new int[S.length()];
        Arrays.fill(match, -1);

        for (int i = 0; i < sources.length; i++) {
            String source = sources[i];
            if (S.substring(indexes[i], indexes[i] + source.length()).equals(source)) {
                match[indexes[i]] = i;
            }
        }

        int i = 0;
        while (i < S.length()) {
            if (match[i] >= 0) {
                sb.append(targets[match[i]]);
                i += sources[match[i]].length();
            } else {
                sb.append(S.charAt(i));
                i++;
            }
        }

        return sb.toString();
    }
}

Complexity

  • time: O(NQ), N is length of S, Q is number of append times
  • space: O(N)