GuilinDev

Lc1910

05 August 2008

1910 Remove All Occurrences of a Substring

给一个字符串和其子字符串,从左边删除子字符串,循环往复返回最后剩的

模拟

1
2
3
4
5
6
7
8
9
class Solution {
  public String removeOccurrences(String s, String part) {
    while (s.contains(part)) {
      int i = s.indexOf(part);
      s = s.substring(0, i) + s.substring(i + part.length());
    }
    return s;
  }
}
1
2
3
4
5
6
7
8
class Solution {
    public String removeOccurrences(String s, String part) {
        if (!s.contains(part)) {
            return s;
        }
        return removeOccurrences(s.replaceFirst(part, ""), part);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
    public String removeOccurrences(String s, String part) {
        int n = s.length();
        int m = part.length();
        if (m > n) {
            return s;
        }
        for (int i = 0; i < n - m + 1; i++) {
            if (s.substring(i, i + m).equals(part)) {
                s = s.substring(0, i) + s.substring(i + m);
                return removeOccurrences(s, part);
            }
        }
        return s;
    }
}