Approach
Sorting and greedy selection
For Find And Replace in String, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 21 lines of Java from the credited upstream file 833.java.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public String findReplaceString(String s, int[] indices, String[] sources, String[] targets) {3 record Operation(int index, String source, String target) {}4 Operation[] operations = new Operation[indices.length];5 6 for (int i = 0; i < indices.length; ++i)7 operations[i] = new Operation(indices[i], sources[i], targets[i]);8 9 Arrays.sort(operations, Comparator.comparing(Operation::index, Comparator.reverseOrder())10 .thenComparing(Operation::source, Comparator.reverseOrder())11 .thenComparing(Operation::target, Comparator.reverseOrder()));12 13 for (Operation op : operations)14 if (s.substring(op.index, Math.min(op.index + op.source.length(), s.length()))15 .equals(op.source))16 s = s.substring(0, op.index) + op.target + s.substring(op.index + op.source.length());17 18 return s;19 }20}21