-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathRemoveAllOccurrencesofaSubstring.java
80 lines (55 loc) · 1.8 KB
/
RemoveAllOccurrencesofaSubstring.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
Source: https://leetcode.com/problems/remove-all-occurrences-of-a-substring/
1st approach
Time: O(m * n), where m is the length of the given String(s) and n is the length of the string(part)
Space: O(n), StringBuilder is needed to append characters of given String(s)
*/
class Solution {
public String removeOccurrences(String s, String part) {
StringBuilder res = new StringBuilder();
int partLen = part.length();
for(char ch : s.toCharArray()) {
res.append(ch);
int resLen = res.length();
if(resLen >= partLen) {
if(res.substring(resLen - partLen).equals(part)) {
res.setLength(resLen - partLen);
}
}
}
return res.toString();
}
}
/*
2nd approach (More optimzed than the 1st approach)
Time: O(m * n), where m is the length of the given string(s) and n is the length of the string(part)
Space: O(1), in-place
*/
class Solution {
public String removeOccurrences(String s, String part) {
int partLen = part.length();
int index = s.indexOf(part);
while(index != -1) {
s = s.substring(0, index) + s.substring(index + partLen);
index = s.indexOf(part);
}
return s;
}
}
/*
3rd approach (More optimzed than the 2nd approach)
Time: O(m * n), where m is the length of the given string(s) and n is the length of the string(part)
Space: O(n), for the given String(s), an equivalent StringBuider object is needed
*/
class Solution {
public String removeOccurrences(String s, String part) {
StringBuilder res = new StringBuilder(s);
int partLen = part.length();
int index = res.indexOf(part);
while(index != -1) {
res.delete(index, index + partLen);
index = res.indexOf(part, index - partLen); // indexOf(string, fromIndex) to avoid starting from 0
}
return res.toString();
}
}