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

Commitefd6874

Browse files
committed
str
1 parentd7fbfef commitefd6874

File tree

1 file changed

+55
-1
lines changed

1 file changed

+55
-1
lines changed

‎string/FindSubstring.java

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ public static void main(String[] strs) {
1111
System.out.println(findSubstring("lingmindraboofooowingdingbarrwingmonkeypoundcake",L));
1212
}
1313

14-
publicstaticList<Integer>findSubstring(StringS,String[]L) {
14+
publicstaticList<Integer>findSubstring1(StringS,String[]L) {
1515
HashMap<String,Integer>map =newHashMap<String,Integer>();
1616
HashMap<String,Integer>found =newHashMap<String,Integer>();
1717
List<Integer>ret =newArrayList<Integer>();
@@ -76,4 +76,58 @@ public static List<Integer> findSubstring(String S, String[] L) {
7676

7777
returnret;
7878
}
79+
80+
// SOLUTION 2:
81+
publicstaticList<Integer>findSubstring(StringS,String[]L) {
82+
HashMap<String,Integer>map =newHashMap<String,Integer>();
83+
HashMap<String,Integer>found;
84+
List<Integer>ret =newArrayList<Integer>();
85+
86+
if (S ==null ||L ==null ||L.length ==0) {
87+
returnret;
88+
}
89+
90+
// put all the strings into the map.
91+
for (Strings:L) {
92+
if (map.containsKey(s)) {
93+
map.put(s,map.get(s) +1);
94+
}else {
95+
map.put(s,1);
96+
}
97+
}
98+
99+
intlenL =L[0].length();
100+
101+
// 注意这里的条件:i < S.length() - lenL * L.length
102+
// 这里很关键,如果长度不够了,不需要再继续查找
103+
for (inti =0;i <=S.length() -lenL *L.length;i++) {
104+
// 每一次,都复制之前的hashMap.
105+
found =newHashMap<String,Integer>(map);
106+
107+
// 一次前进一个L的length.
108+
// 注意j <= S.length() - lenL; 防止越界
109+
for (intj =i;j <=S.length() -lenL;j +=lenL) {
110+
Stringsub =S.substring(j,j +lenL);
111+
if (found.containsKey(sub)) {
112+
// 将找到字符串的计数器减1.
113+
found.put(sub,found.get(sub) -1);
114+
115+
// 减到0即可将其移出。否则会产生重复运算,以及我们用MAP为空来判断是否找到所有的单词。
116+
if (found.get(sub) ==0) {
117+
found.remove(sub);
118+
}
119+
}else {
120+
// 不符合条件,可以break,i前进到下一个匹配位置
121+
break;
122+
}
123+
124+
// L中所有的字符串都已经找到了。
125+
if (found.isEmpty()) {
126+
ret.add(i);
127+
}
128+
}
129+
}
130+
131+
returnret;
132+
}
79133
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp