Skip to content

Commit c74d8f8

Browse files
committed
[Optimize the code]: Have implemented the program to find the final string after removing all the occurrences of a substring:.
1 parent cd23e21 commit c74d8f8

File tree

2 files changed

+27
-25
lines changed

2 files changed

+27
-25
lines changed

.idea/workspace.xml

Lines changed: 20 additions & 21 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/com/raj/RemoveAllOccurrencesOfASubstring.java

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,18 +12,21 @@ public static void main(String[] args) {
1212
StringBuilder ans = new StringBuilder(s);
1313

1414
// Logic.
15-
recursiveStringReplace(ans, part);
15+
recursiveStringReplace(ans, part, 0);
1616

1717
// Display the result.
1818
System.out.println("The final string after removing all the occurrences of a substring: " + ans + ".");
1919
}
2020

2121
// Recursive call the function itself to replace the string with the part.
22-
private static void recursiveStringReplace(StringBuilder s, String part) {
23-
for (int i = 0; i <= s.length() - part.length(); i++) {
22+
private static void recursiveStringReplace(StringBuilder s, String part, int startIndex) {
23+
for (int i = startIndex; i <= s.length() - part.length(); i++) {
2424
if (s.substring(i, i + part.length()).equals(part)) {
2525
s.delete(i, i + part.length());
26-
recursiveStringReplace(s, part);
26+
if (i - part.length() > 0) {
27+
startIndex = i - part.length();
28+
}
29+
recursiveStringReplace(s, part, startIndex);
2730
}
2831
}
2932
}

0 commit comments

Comments
 (0)