-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathPermutation_in_String.java
54 lines (46 loc) · 1.68 KB
/
Permutation_in_String.java
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
//Leetcode 567. Permutation in String
//Question - https://leetcode.com/problems/permutation-in-string/
class Solution {
public boolean checkInclusion(String s1, String s2) {
if(s1.length()==0 && s2.length()==0) return true;
else if(s1.length()==0) return true;
else if(s2.length()==0) return false;
//We are supposed to check if 's2' contains the anagram of 's1'
HashMap<Character,Integer> freqTable = new HashMap<>();
int freq = -1;
for(int i=0;i<s1.length();i++){
char curr = s1.charAt(i);
freq = freqTable.getOrDefault(curr,0);
freq++;
freqTable.put(curr,freq);
}
//System.out.println(freqTable);
int end = 0;
int start = 0;
int counter = freqTable.size();
while(end < s2.length()){
char endChar = s2.charAt(end);
if(freqTable.containsKey(endChar)){
freq = freqTable.get(endChar);
freq--;
freqTable.put(endChar,freq);
if(freq==0) counter--;
}
end++;
while(counter==0){
char startChar = s2.charAt(start);
if(end-start==s1.length()){
return true;
}
if(freqTable.containsKey(startChar)){
freq = freqTable.get(startChar);
freq++;
freqTable.put(startChar,freq);
if(freq>0) counter++;
}
start++;
}
}
return false;
}
}