Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 0411745

Browse files
committed
[Without for loop]: Have implemented the program to find the final string after removing all the occurrences of a substring.
1 parent f0ec9f4 commit 0411745

File tree

2 files changed

+25
-27
lines changed

2 files changed

+25
-27
lines changed

.idea/workspace.xml

Lines changed: 19 additions & 19 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: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,20 +12,18 @@ public static void main(String[] args) {
1212
StringBuilder ans = new StringBuilder(s);
1313

1414
// Logic.
15-
recursiveStringReplace(ans, part, 0);
15+
recursiveStringReplace(ans, part);
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, int startIndex) {
23-
for (int i = startIndex; i <= s.length() - part.length(); i++) {
24-
if (s.substring(i, i + part.length()).equals(part)) {
25-
s.delete(i, i + part.length());
26-
startIndex = Math.max(i - part.length(), 0);
27-
recursiveStringReplace(s, part, startIndex);
28-
}
22+
private static void recursiveStringReplace(StringBuilder s, String part) {
23+
int subStringStartIndex = s.indexOf(part);
24+
if (subStringStartIndex != -1) {
25+
s.delete(subStringStartIndex, subStringStartIndex + part.length());
26+
recursiveStringReplace(s, part);
2927
}
3028
}
3129
}

0 commit comments

Comments
 (0)