LeetCode-in-Java

1910. Remove All Occurrences of a Substring

Medium

Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed:

Return s after removing all occurrences of part.

A substring is a contiguous sequence of characters in a string.

Example 1:

Input: s = “daabcbaabcbc”, part = “abc”

Output: “dab”

Explanation: The following operations are done:

Example 2:

Input: s = “axxxxyyyyb”, part = “xy”

Output: “ab”

Explanation: The following operations are done:

Constraints:

Solution

public class Solution {
    public String removeOccurrences(String s, String part) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            sb.append(s.charAt(i));
            if (sb.length() >= part.length()
                    && sb.substring(sb.length() - part.length()).equals(part)) {
                sb.setLength(sb.length() - part.length());
            }
        }
        return sb.toString();
    }
}