Skip to content

Commit aeed40d

Browse files
committed
add solution of problem 428: find all anagrams in a string
1 parent c5c0be6 commit aeed40d

2 files changed

Lines changed: 101 additions & 0 deletions

File tree

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
Given a string **s** and a **non-empty** string **p**, find all the start indices of **p**'s anagrams in **s**.
2+
3+
Strings consists of lowercase English letters only and the length of both strings **s** and **p** will not be larger than 20,100.
4+
5+
The order of output does not matter.
6+
7+
#####Example 1:
8+
```
9+
10+
######Input:
11+
s: "cbaebabacd" p: "abc"
12+
13+
######Output:
14+
[0, 6]
15+
16+
######Explanation:
17+
The substring with start index = 0 is "cba", which is an anagram of "abc".
18+
The substring with start index = 6 is "bac", which is an anagram of "abc".
19+
20+
```
21+
#####Example 2:
22+
```
23+
24+
######Input:
25+
s: "abab" p: "ab"
26+
27+
######Output:
28+
[0, 1, 2]
29+
30+
######Explanation:
31+
The substring with start index = 0 is "ab", which is an anagram of "ab".
32+
The substring with start index = 1 is "ba", which is an anagram of "ab".
33+
The substring with start index = 2 is "ab", which is an anagram of "ab".
34+
35+
```
36+
37+
####思路
38+
只包含小写字母,因此可用26个char的数组作为哈希表,O(1)查找
39+
然后用KMP来移动指针
40+
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
public class Solution {
2+
public List<Integer> findAnagrams(String s, String p) {
3+
List<Integer> result = new ArrayList<Integer>();
4+
Set<Character> charSet = new HashSet<Character>();
5+
6+
for (int i = 0; i < p.length(); i++)
7+
charSet.add(p.charAt(i));
8+
9+
int i = 0;
10+
while (i < s.length()) {
11+
int[] map = getMap(p);
12+
boolean matched = false;
13+
int cnt = 0;
14+
int j = i;
15+
16+
for (; j < s.length(); j++) {
17+
if (map[s.charAt(j) - 'a'] > 0) {
18+
map[s.charAt(j) - 'a']--;
19+
cnt++;
20+
21+
if (cnt == p.length()) {
22+
result.add(i);
23+
matched = true;
24+
break;
25+
}
26+
} else if (cnt < p.length()) {
27+
break;
28+
}
29+
}
30+
31+
if (matched) {
32+
i++;
33+
} else if (j < s.length() && charSet.contains(s.charAt(j))) {
34+
i++;
35+
} else {
36+
if (i == j) {
37+
if (charSet.contains(s.charAt(j)))
38+
i = j;
39+
else
40+
i = j + 1;
41+
}
42+
else {
43+
i = j;
44+
}
45+
}
46+
47+
}
48+
49+
return result;
50+
}
51+
52+
private int[] getMap(String p) {
53+
int[] map = new int[26];
54+
55+
for (int i = 0; i < p.length(); i++) {
56+
map[p.charAt(i) - 'a']++;
57+
}
58+
59+
return map;
60+
}
61+
}

0 commit comments

Comments
 (0)