Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitd7fbfef

Browse files
committed
find string
1 parent04d3b40 commitd7fbfef

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

‎string/FindSubstring.java

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
packageAlgorithms.string;
2+
3+
importjava.util.ArrayList;
4+
importjava.util.HashMap;
5+
importjava.util.List;
6+
7+
publicclassFindSubstring {
8+
publicstaticvoidmain(String[]strs) {
9+
String[]L = {"fooo","barr","wing","ding","wing"};
10+
11+
System.out.println(findSubstring("lingmindraboofooowingdingbarrwingmonkeypoundcake",L));
12+
}
13+
14+
publicstaticList<Integer>findSubstring(StringS,String[]L) {
15+
HashMap<String,Integer>map =newHashMap<String,Integer>();
16+
HashMap<String,Integer>found =newHashMap<String,Integer>();
17+
List<Integer>ret =newArrayList<Integer>();
18+
19+
if (S ==null ||L ==null ||L.length ==0) {
20+
returnret;
21+
}
22+
23+
intcntL =0;
24+
25+
// put all the strings into the map.
26+
for (Strings:L) {
27+
if (map.containsKey(s)) {
28+
map.put(s,map.get(s) +1);
29+
}else {
30+
map.put(s,1);
31+
cntL++;
32+
}
33+
}
34+
35+
intlenL =L[0].length();
36+
37+
intcntFound =0;
38+
39+
// 注意这里的条件:i < S.length() - lenL * L.length
40+
// 这里很关键,如果长度不够了,不需要再继续查找
41+
for (inti =0;i <=S.length() -lenL *L.length;i++) {
42+
// clear the found hashmap.
43+
found.clear();
44+
cntFound =0;
45+
46+
// 一次前进一个L的length.
47+
// 注意j <= S.length() - lenL; 防止越界
48+
for (intj =i;j <=S.length() -lenL;j +=lenL) {
49+
Stringsub =S.substring(j,j +lenL);
50+
if (map.containsKey(sub)) {
51+
if (found.containsKey(sub)) {
52+
if (found.get(sub) ==map.get(sub)) {
53+
// 超过了限制数目
54+
break;
55+
}
56+
57+
found.put(sub,found.get(sub) +1);
58+
}else {
59+
found.put(sub,1);
60+
}
61+
62+
if (found.get(sub) ==map.get(sub)) {
63+
cntFound++;
64+
}
65+
66+
// L中所有的字符串都已经找到了。
67+
if (cntFound ==cntL) {
68+
ret.add(i);
69+
}
70+
}else {
71+
// 不符合条件,可以break,i前进到下一个匹配位置
72+
break;
73+
}
74+
}
75+
}
76+
77+
returnret;
78+
}
79+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp