8000 Merge pull request #105 from qilingit/day17 · qilingit/Leetcode@0648bda · GitHub
[go: up one dir, main page]

Skip to content

Commit 0648bda

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

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

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

Lines 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