-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfindSubstring.java
More file actions
executable file
·56 lines (52 loc) · 1.73 KB
/
findSubstring.java
File metadata and controls
executable file
·56 lines (52 loc) · 1.73 KB
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
/*
You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.
For example, given:
S: "barfoothefoobarman"
L: ["foo", "bar"]
You should return the indices: [0,9].
(order does not matter).
*/
import java.util.*;
public class findSubstring{
public static void main(String[] args) {
String S = "barfoothefoobarman";
String[] L = {"foo","bar"};
List<Integer> res = findSub(S, L);
System.out.println(res);
}
public static List<Integer> findSub(String S, String[] L){
List<Integer> res = new ArrayList<Integer>();
if(S == null || L == null)
return res;
if(L[0].length()*L.length > S.length())
return res;
HashMap<String,Integer> Lmap = new HashMap<String,Integer>();
HashMap<String,Integer> Cmap = new HashMap<String,Integer>();
for(String t : L)
if(!Lmap.containsKey(t))
Lmap.put(t,1);
else
Lmap.put(t,Lmap.get(t) + 1);
int wordSize = L[0].length();
int numStr = L.length;
for(int i = 0; i < S.length() - numStr*wordSize + 1; ++i){
if(!Cmap.isEmpty())
Cmap.clear();
int j = 0;
for(j = 0; j < numStr; ++j){
String tr = S.substring(i+j*wordSize,i+(j+1)*wordSize);
if(!Lmap.containsKey(tr))
break;
if(!Cmap.containsKey(tr))
Cmap.put(tr,1);
else{
Cmap.put(tr,Cmap.get(tr) + 1);
if(Cmap.get(tr) > Lmap.get(tr))
break;
}
}
if(j == numStr) res.add(i);
}
return res;
}
}