833. Find And Replace in String

T: O(m+n), m is indices, sources, targets array size (same), n is s len

S: O(sb len + hashmap size)

class Solution {
    public String findReplaceString(String s, int[] indices, String[] sources, String[] targets) {
        // HashMap(origin string start index, indices index)
        Map<Integer, Integer> map = new HashMap<>(); t index)
        for (int i = 0; i < indices.length;i++) {
            String substring = s.substring(indices[i], indices[i] + sources[i].length());
            if (substring.equals(sources[i])) {
                map.put(indices[i], i);
            }
        }
        
        StringBuilder sb = new StringBuilder();
        int i = 0;
        while (i < s.length()) {
            if (map.containsKey(i)) {
                int arrayIdx = map.get(i);
                sb.append(targets[arrayIdx]);
                i += sources[arrayIdx].length();
            } else {
                sb.append(s.charAt(i));
                i++;
            }
        }
        return sb.toString();
    }
}

/*
O(m), m is indices, sources, targets array size (same)
for indices
s -> check sources[i] in s's indices[i]? 
    yes => put in HashMap (indices[i], i), HashMap(origin index, array element index)
    
    
O(n), n is s len
    StringBuilder sb
    for i in s
        if i in map
            int arrayIdx = map.get(i)
            sb.append(targets[arrayIdx])
            i += sources[arrayIdx].length()
        else 
            sb.append(s[i])
            i++
*/

Last updated