You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
* • Create a map where the key is the index in the string s where a valid replacement can occur, and the value is the index in the sources and targets arrays.
75
+
*
76
+
* • Logic:
77
+
* • Loop through each replacement instruction (indices, sources, targets).
78
+
* • Check if sources[i] exists as a substring of s starting at indices[i]:
79
+
* • Use s.startsWith(sources[i], indices[i]) to verify this condition.
80
+
* • If the condition is true, store the index (indices[i]) in the map with its corresponding sources/targets index (i).
81
+
*
82
+
* • Result:
83
+
* • The map will only contain valid replacement indices, ensuring that only valid replacements are performed.
84
+
*
85
+
*/
70
86
Map<Integer, Integer> map = newHashMap<>();
71
87
for (inti = 0; i < indices.length; i++) {
72
88
if (s.startsWith(sources[i], indices[i])) {
73
89
map.put(indices[i], i);
74
90
}
75
91
}
92
+
93
+
/**
94
+
* • Purpose:
95
+
* • Construct the final string using a StringBuilder, processing each character of s sequentially.
96
+
*
97
+
* • Logic:
98
+
* • Case 1: If the current index i is not in the map, it means no replacement starts at this index.
99
+
* • Append the character at s[i] to the StringBuilder and move to the next character (i++).
100
+
* • Case 2: If the current index i is in the map, it means a valid replacement starts here.
101
+
* • Retrieve the corresponding index from map.get(i) and:
102
+
* • Append the replacement string (targets[map.get(i)]) to the StringBuilder.
103
+
* • Skip over the characters in the source substring (i += sources[map.get(i)].length()).
104
+
*
105
+
*
106
+
* • Why Use StringBuilder:
107
+
* • Strings in Java are immutable, so using StringBuilder allows efficient in-place concatenation.
0 commit comments