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

Appearance settings

Commit bc56889

Browse filesBrowse files
committed
Add java solution for Day17 Find All Anagrams In a String
1 parent 7f7fdfe commit bc56889
Copy full SHA for bc56889

File tree

Expand file treeCollapse file tree

1 file changed

+40
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+40
-0
lines changed
+40Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
* Use a int[26] to store char count,
3+
* compare between p count and each s substring count.
4+
*/
5+
class Solution {
6+
public List<Integer> findAnagrams(String s, String p) {
7+
List<Integer> res = new ArrayList<>();
8+
if (s.length() - p.length() < 0) {
9+
return res;
10+
}
11+
int[] pCount = transform(p.toCharArray(), 0, p.length());
12+
char[] sArray = s.toCharArray();
13+
int[] strCount = transform(sArray, 0, p.length());
14+
if (Arrays.equals(strCount, pCount))
15+
res.add(0);
16+
for (int i = 0; i < s.length() - p.length(); i++) {
17+
if (moveAndCompare(sArray, strCount, i, i + p.length(), pCount))
18+
res.add(i + 1);
19+
}
20+
return res;
21+
}
22+
23+
public int[] transform(char[] s, int begin, int end) {
24+
int[] count = new int[26];
25+
for (int i = begin; i < end; i++) {
26+
char c = s[i];
27+
int idx = c - 'a';
28+
count[idx] += 1;
29+
}
30+
return count;
31+
}
32+
33+
public boolean moveAndCompare(char[] str, int[] strCount, int toRemove, int toAdd, int[] pCount) {
34+
int toRemoveIdx = str[toRemove] - 'a';
35+
strCount[toRemoveIdx] -= 1;
36+
int toAddIdx = str[toAdd] - 'a';
37+
strCount[toAddIdx] += 1;
38+
return Arrays.equals(strCount, pCount);
39+
}
40+
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.