-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFinding the first occurence of a pattern in a string
71 lines (58 loc) · 1.38 KB
/
Finding the first occurence of a pattern in a string
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
71
Implement strstr
https://www.geeksforgeeks.org/problems/implement-strstr/1
-----------------------------------------------------------------
class GfG
{
//Function to locate the occurrence of the string x in the string s.
void LPS(String s, int[] lps)
{
int len = 0, i=1, n=s.length();
lps[0] = 0;
while(i<n)
{
if(s.charAt(i) == s.charAt(len))
{
len++;
lps[i] = len;
i++;
}
else
{
if(len == 0)
{lps[i] = 0; i++;}
else
{
len = lps[len-1];
}
}
}
}
int strstr(String s, String x)
{
// Your code here
int n1=s.length(), n2 = x.length();
int[] lps = new int[n2];
LPS(x, lps);
int res = -1;
int i=0, j=0;
int c=0;
while(i<n1)
{
if(s.charAt(i) == x.charAt(j))
{ i++; j++; }
if(j == n2)
{
res = i-j;
j = lps[j-1];
break;
}
else if(i<n1 && s.charAt(i) != x.charAt(j))
{
if(j==0) i++;
else
j=lps[j-1];
}
}
return res;
}
}