-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathProblem_6.java
More file actions
59 lines (46 loc) · 1.87 KB
/
Problem_6.java
File metadata and controls
59 lines (46 loc) · 1.87 KB
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
package strings;
import java.util.Scanner;
// * Check whether a string is valid shuffle of two strings or not
public class Problem_6 {
// function to compareCharacterCounts
static boolean compareCharacterCounts(int[] charCount1, int[] charCount2) {
for (int i = 0; i < 256; i++)
if (charCount1[i] != charCount2[i])
return false;
return true;
}
// This function searchForPattern for all permutations of pat[] in txt[]
static boolean searchForPattern(String pattern, String text) {
int patternLength = pattern.length();
int textLength = text.length();
int[] patternCharCount = new int[256];
int[] currentWindowCharCount = new int[256];
for (int i = 0; i < 256; i++) {
patternCharCount[i] = 0;
currentWindowCharCount[i] = 0;
}
for (int i = 0; i < patternLength; i++) {
(patternCharCount[pattern.charAt(i)])++;
(currentWindowCharCount[text.charAt(i)])++;
}
for (int i = patternLength; i < textLength; i++) {
if (compareCharacterCounts(patternCharCount, currentWindowCharCount))
return true;
(currentWindowCharCount[text.charAt(i)])++; // Add current character to current window
currentWindowCharCount[text.charAt(i - patternLength)]--; // Remove the first character of previous window
}
// Check for the last window in text
return compareCharacterCounts(patternCharCount, currentWindowCharCount);
}
// Driver code
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String txt = sc.nextLine();
String pat = sc.nextLine();
if (searchForPattern(pat, txt))
System.out.println("Yes");
else
System.out.println("NO");
sc.close();
}
}