Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update 0567-permutation-in-string.java #3496

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 52 additions & 13 deletions java/0567-permutation-in-string.java
Original file line number Diff line number Diff line change
@@ -1,20 +1,59 @@
public class Solution {
class Solution {

public boolean checkInclusion(String s1, String s2) {

int n = s1.length();
int[] freq = new int[26];
int m = s2.length();
for (int i = 0; i < n; i++) {
freq[s1.charAt(i) - 'a']++;
}
int[] freq2 = new int[26];
for (int i = 0; i < m; i++) {
freq2[s2.charAt(i) - 'a']++;
if (i >= n) {
freq2[s2.charAt(i - n) - 'a']--;
}
if (Arrays.equals(freq, freq2))

if(n > m)
return false;

int[] f1 = new int[26];
int[] f2 = new int[26];

for(int i=0; i<n; i++)
f1[s1.charAt(i)-'a']++;

for(int i=0; i<n; i++) // we will iterate only till n chars since those will form the initial permutation
f2[s2.charAt(i)-'a']++;

if (Arrays.equals(f1, f2))
return true;

int idx = n; // start of next window

while(idx < m){

// we have moved the window one step towards right
// so freq of char at idx should increase
// and freq of left most char in prev window should decrease
char newChar = s2.charAt(idx);
char prevChar = s2.charAt(idx-n);

f2[newChar-'a']++;
f2[prevChar-'a']--;

if (Arrays.equals(f1, f2))
return true;

idx++;

}

return false;

}

public int initializeMatch(int[] f1, int[] f2){

int count = 0;

for(int i=0; i<26; i++){
if(f1[i] == f2[i])
count++;
}

return count;
}
}

}