|
| 1 | +package solutions; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.Map; |
| 6 | + |
| 7 | +// [Problem] https://leetcode.com/problems/find-and-replace-in-string |
| 8 | +class FindAndReplaceInString { |
| 9 | + // String and sorting |
| 10 | + // O(nlogn) time, O(n) space |
| 11 | + public String findReplaceString(String s, int[] indices, String[] sources, String[] targets) { |
| 12 | + Map<Integer, Integer> indexMap = new HashMap<>(); |
| 13 | + for (int i = 0; i < indices.length; i++) { |
| 14 | + indexMap.put(indices[i], i); |
| 15 | + } |
| 16 | + Arrays.sort(indices); |
| 17 | + StringBuilder result = new StringBuilder(); |
| 18 | + int pointer = 0; |
| 19 | + for (int currentIndex : indices) { |
| 20 | + int i = indexMap.get(currentIndex); |
| 21 | + String source = sources[i]; |
| 22 | + int nextIndex = currentIndex + source.length(); |
| 23 | + if (source.equals(s.substring(currentIndex, nextIndex))) { |
| 24 | + result.append(s.substring(pointer, currentIndex)); |
| 25 | + result.append(targets[i]); |
| 26 | + pointer = nextIndex; |
| 27 | + } |
| 28 | + } |
| 29 | + result.append(s.substring(pointer)); |
| 30 | + return result.toString(); |
| 31 | + } |
| 32 | + |
| 33 | + // Test |
| 34 | + public static void main(String[] args) { |
| 35 | + FindAndReplaceInString solution = new FindAndReplaceInString(); |
| 36 | + |
| 37 | + String s = "abcd"; |
| 38 | + int[] indices = {0, 2}; |
| 39 | + String[] sources = {"a", "cd"}; |
| 40 | + String[] targets = {"eee", "ffff"}; |
| 41 | + String expectedOutput = "eeebffff"; |
| 42 | + String actualOutput = solution.findReplaceString(s, indices, sources, targets); |
| 43 | + |
| 44 | + System.out.println("Test passed? " + expectedOutput.equals(actualOutput)); |
| 45 | + } |
| 46 | +} |
0 commit comments