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

Commita506c74

Browse files
author
applewjg
committed
add solution
Change-Id: Ic1bd940f0fbac1a9a73f4057efdb1f15b1adf460
1 parentb26c1e6 commita506c74

File tree

1 file changed

+41
-3
lines changed

1 file changed

+41
-3
lines changed

‎SubstringwithConcatenationofAllWords.java

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
Author:King, wangjingui@outlook.com
2+
Author:Andy, nkuwjg@gmail.com
33
Date: Dec 20, 2014
44
Problem: Substring with Concatenation of All Words
55
Difficulty: Easy
@@ -14,10 +14,11 @@ starting indices of substring(s) in S that is a concatenation of each word in L
1414
You should return the indices: [0,9].
1515
(order does not matter).
1616
17-
Solution: ...
17+
Solution: 1. Brute + HashMap.
18+
2. Sliding Window + HashMap. from Sun Mian.
1819
*/
1920
publicclassSolution {
20-
publicList<Integer>findSubstring(StringS,String[]L) {
21+
publicList<Integer>findSubstring_1(StringS,String[]L) {
2122
List<Integer>res =newArrayList<Integer>();
2223
if(L.length==0 ||S==null ||S.length()==0)returnres;
2324
intM =S.length(),N =L.length;
@@ -45,4 +46,41 @@ public List<Integer> findSubstring(String S, String[] L) {
4546
}
4647
returnres;
4748
}
49+
50+
publicList<Integer>findSubstring_2(StringS,String[]L) {
51+
List<Integer>list =newArrayList<>();
52+
Map<String,Integer>need =newHashMap<>();
53+
for(Stringstr:L) {
54+
if(need.containsKey(str)) {
55+
need.put(str,need.get(str)+1);
56+
}else {
57+
need.put(str,1);
58+
}
59+
}
60+
intn =L[0].length(),m =L.length;
61+
for (inti =0;i <n; ++i) {
62+
Map<String,Integer>find =newHashMap<>();
63+
for (intstart =i,end =i,count =0;end +n <=S.length();end +=n) {
64+
Stringstr =S.substring(end,end +n);
65+
if (need.get(str) ==null) {
66+
start =end +n;
67+
find.clear();
68+
count =0;
69+
continue;
70+
}
71+
while (find.get(str) !=null &&find.get(str) >=need.get(str)) {
72+
StringsubStart =S.substring(start,start +n);
73+
find.put(subStart,find.get(subStart) -1);
74+
start +=n;
75+
--count;
76+
}
77+
find.put(str, (find.get(str) ==null ?0 :find.get(str)) +1);
78+
++count;
79+
if (count !=m)continue;
80+
list.add(start);
81+
}
82+
}
83+
returnlist;
84+
}
85+
4886
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp