-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathSearch_Pattern.java
More file actions
49 lines (43 loc) · 1.08 KB
/
Search_Pattern.java
File metadata and controls
49 lines (43 loc) · 1.08 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
// { Driver Code Starts
//Initial Template for Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String args[]) throws IOException {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
String s, patt;
s = sc.next();
patt = sc.next();
Solution ob = new Solution();
ArrayList<Integer> res = ob.search(patt, s);
if (res.size() == 0)
System.out.print("-1 ");
else {
for (int i = 0; i < res.size(); i++)
System.out.print(res.get(i) + " ");
}
System.out.println();
}
}
}
class Solution {
ArrayList<Integer> search(String pat, String S) {
ArrayList<Integer> ans = new ArrayList<>();
int i = 0;
while (i < S.length()) {
while (i < S.length() && S.charAt(i) != pat.charAt(0))
i++;
int j = 0, k = i;
while (k < S.length() && j < pat.length() && S.charAt(k) == pat.charAt(j)) {
k++;
j++;
}
if (j == pat.length() && k <= S.length())
ans.add(i + 1);
i++;
}
return ans;
}
}