- Find All Anagrams in a String:题目链接
方法1:双指针之滑动窗口
1 | import java.util.ArrayList; |
另外一种用map的方法,但是效率不知道为什么非常低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
39import java.util.*;
public class Solution2 {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> list = new ArrayList<>();
Map<Character, Integer> ms = new HashMap<>();
Map<Character, Integer> mp = new HashMap<>();
Vector v = new Vector();
for (int i =0; i<p.length();++i) {
mp.put(p.charAt(i), mp.getOrDefault(p.charAt(i), 0) + 1);
}
int left = 0, right = 0;
while (right < s.length()){
ms.put(s.charAt(right), ms.getOrDefault(s.charAt(right), 0) + 1);
right++;
if (right - left == p.length()){
if (ms.equals(mp)) {
list.add(left);
}
char ch = s.charAt(left);
if (ms.get(ch) > 1){
ms.put(ch, ms.get(ch)-1);
}else{
ms.remove(ch);
}
left++;
}
}
return list;
}
public static void main(String[] args) {
String s = "cbaebabacd";
String p = "abc";
System.out.println(new Solution2().findAnagrams(s, p));
}
}
pS:
源代码链接