-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRepeatSubstring.java
72 lines (60 loc) · 1.77 KB
/
RepeatSubstring.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
// LeetCode_1669
// 2021.04.22
// Easy
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class RepeatSubstring {
public static void main(String[] args) {
System.out.println(new RepeatSubstring().maxRepeating("ababc","ab"));
}
public int maxRepeating(String sequence, String word) {
List<Integer> list = new ArrayList<>();
String subSequence = sequence;
StringBuilder str;
int cnt = 0;
int preIdx = word.length();
int tmp = 0;
list.add(0);
while(subSequence.contains(word)) {
str = checkSubstring(subSequence, word);
subSequence = str.toString();
if(preIdx == sequence.indexOf(word)+word.length()) {
cnt++;
tmp = cnt;
}
else{
list.add(cnt);
cnt = 1;
}
sequence = subSequence;
}
if(list.size() == 1)
list.add(tmp);
list.sort(Comparator.reverseOrder());
return list.get(0);
}
public static StringBuilder checkSubstring(String str, String word){
StringBuilder s = new StringBuilder(str);
String subString ="";
if(s.indexOf(word) != -1){
subString = s.substring(s.indexOf(word) + word.length(), s.length());
}
return new StringBuilder(subString);
}
}
/* simple Solution..출처: LeetCode
public int maxRepeating(String sequence, String word) {
String w1 = word;
int res = 0;
while (w1.length() <= sequence.length()) {
if (sequence.contains(w1)) {
res++;
w1 += word;
} else {
break;
}
}
return res;
}
*/