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 0648bda

Browse filesBrowse files
authored
Merge pull request #105 from qilingit/day17
Add java sliding window solution for day17: Find All Anagrams in a String
2 parents c4794d9 + 8cfc915 commit 0648bda
Copy full SHA for 0648bda

File tree

Expand file treeCollapse file tree

1 file changed

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

1 file changed

+33
-0
lines changed

‎May-LeetCoding-Challenge/17-Find-All-Anagrams-In-A-String/Find-All-Anagrams-In-A-String.java

Copy file name to clipboardExpand all lines: May-LeetCoding-Challenge/17-Find-All-Anagrams-In-A-String/Find-All-Anagrams-In-A-String.java
+33Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,39 @@ public List<Integer> findAnagrams(String s, String p) {
6767
if(isAnagram(subString, p)) res.add(i);
6868
}
6969

70+
return res;
71+
}
72+
}
73+
74+
// Sliding windows solution
75+
class Solution3 {
76+
private boolean checkDiff(int[] diff){
77+
for (int i = 0; i < diff.length; i++)
78+
if (diff[i] != 0) return false;
79+
80+
return true;
81+
}
82+
83+
public List<Integer> findAnagrams(String s, String p) {
84+
List<Integer> res = new ArrayList<>();
85+
int sLength = s.length(), pLength = p.length();
86+
if(sLength < pLength || s == null) return res;
87+
88+
int[] diff = new int[26];
89+
90+
for(int i = 0; i < pLength; i++) {
91+
diff[p.charAt(i) - 'a']--;
92+
diff[s.charAt(i) - 'a']++;
93+
}
94+
if(checkDiff(diff)) res.add(0);
95+
96+
//sliding window
97+
for (int i = pLength; i < sLength; i++) {
98+
diff[s.charAt(i) - 'a']++;
99+
diff[s.charAt(i - pLength) - 'a']--;
100+
if(checkDiff(diff)) res.add(i - pLength + 1);
101+
}
102+
70103
return res;
71104
}
72105
}

0 commit comments

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