115. Eliminate Substring
Eliminate Substring
You are given two strings s and sub, where both contain only uppercase English letters.
Repeatedly perform the following operation:
Remove one occurrence of the substring sub from s.
After each removal, join the remaining left and right parts of the string. Continue until the string no longer contains sub.
Return the final string. If the final string is empty, return "".
Method
String eliminateSubstring(String s, String sub)
s is the input string
sub is the substring to remove repeatedly until none remain
- return the resulting string
Rules
- Each operation removes one occurrence of
sub.
- After removal, the left and right remaining parts are joined immediately.
- A new occurrence of
sub may be formed after joining.
- The process stops only when
sub no longer appears anywhere in the string.
Constraints
1 ≤ s.length() ≤ 10^5
1 ≤ sub.length() ≤ 10^5
s contains only uppercase English letters
sub contains only uppercase English letters
Examples
Example 1
Input: s = "AWAWSSG", sub = "AWS"
Method Call: eliminateSubstring(s = "AWAWSSG", sub = "AWS")
Output: "G"
Explanation:
Step 1: "AWAWSSG" → "AWSG" (removing one occurrence of "AWS")
Step 2: "AWSG" → "G" (removing one occurrence of "AWS")
Example 2
Input: s = "AWAWSS", sub = "AWS"
Method Call: eliminateSubstring(s = "AWAWSS", sub = "AWS")
Output: ""
Explanation:
Step 1: "AWAWSS" → "AWS" (removing one occurrence of "AWS")
Step 2: "AWS" → "" (removing one occurrence of "AWS")
The final string is empty, so return "".