-
Notifications
You must be signed in to change notification settings - Fork 0
/
PermutationInString.java
70 lines (49 loc) · 1.42 KB
/
PermutationInString.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.leetcode.MayChallenge.week3;
import java.util.Arrays;
/**
* @author Shrinath Joshi
*
* Time complexity:- O(n)
* Space complexity :- O(1)
*
*/
public class PermutationInString {
public boolean checkInclusion(String s1, String s2) {
if (s1.length() == 0 || s2.length() == 0 || s1.length() > s2.length())
return false;
int freqCountS1[] = new int[26];
int freqCountS2[] = new int[26];
for (int i : s1.toCharArray()) {
freqCountS1[i - 'a']++;
}
int n = s1.length();
int m = s2.length();
for (int i = 0; i <=(m - n); i++) {
int left = i;
int right = i + n;
for (int j = left; j < right; j++) {
char currentChar = s2.charAt(j);
freqCountS2[currentChar - 'a']++;
if (checkIfEqual(freqCountS1, freqCountS2)) {
return true;
}
}
Arrays.fill(freqCountS2,0);
}
return false;
}
private boolean checkIfEqual(int[] freqCountS1, int[] freqCountS2) {
for (int i = 0; i < freqCountS1.length; i++) if (freqCountS1[i] != freqCountS2[i])return false;
return true;
}
public static void main(String[] args) {
String s1 = "ab";String s2 = "eidbaooo";
System.out.println(new PermutationInString().checkInclusion(s1, s2));
String s3 = "ab";
String s4 = "eidboaoo";
System.out.println(new PermutationInString().checkInclusion(s3, s4));
String s5 = "adc";
String s6 = "dcda";
System.out.println(new PermutationInString().checkInclusion(s5, s6));
}
}