File tree Expand file tree Collapse file tree 3 files changed +131
-0
lines changed Expand file tree Collapse file tree 3 files changed +131
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ using namespace std ;
3
+
4
+ void fillLPS (string s, int lps[])
5
+ {
6
+ int n = s.length ();
7
+ int len = 0 ;
8
+ int i = 1 ;
9
+ lps[0 ] = 0 ;
10
+ while (i < n)
11
+ {
12
+ if (s[i] == s[len])
13
+ {
14
+ len++;
15
+ lps[i] = len;
16
+ i++;
17
+ }
18
+ else
19
+ {
20
+ if (len == 0 )
21
+ {
22
+ lps[i] = 0 ;
23
+ i++;
24
+ }
25
+ else
26
+ {
27
+ len = lps[len - 1 ];
28
+ }
29
+ }
30
+ }
31
+ }
32
+
33
+ void KMP (string txt, string pat)
34
+ {
35
+ int n = txt.length ();
36
+ int m = pat.length ();
37
+ int lps[m];
38
+ fillLPS (pat, lps);
39
+
40
+ int i = 0 , j = 0 ;
41
+ while (i < n)
42
+ {
43
+ if (txt[i] == pat[j])
44
+ {
45
+ i++;
46
+ j++;
47
+ }
48
+ if (j == m)
49
+ {
50
+ cout << (i - m) << " " ;
51
+ j = lps[j - 1 ];
52
+ }
53
+ else if (i < n && txt[i] != pat[j])
54
+ {
55
+ if (j == 0 )
56
+ i++;
57
+ else
58
+ j = lps[j - 1 ];
59
+ }
60
+ }
61
+ }
62
+
63
+ int main ()
64
+ {
65
+ string txt, pat;
66
+ cin >> txt >> pat;
67
+ KMP (txt, pat);
68
+ return 0 ;
69
+ }
Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ using namespace std ;
3
+
4
+ const int CHAR = 256 ;
5
+
6
+ bool isSame (int a[], int b[])
7
+ {
8
+ for (int i = 0 ; i < CHAR; i++)
9
+ {
10
+ if (a[i] != b[i])
11
+ return false ;
12
+ }
13
+ return true ;
14
+ }
15
+
16
+ bool anagramSeach (string txt, string pat)
17
+ {
18
+ int n = txt.length ();
19
+ int m = pat.length ();
20
+ int ct[CHAR] = {0 };
21
+ int cp[CHAR] = {0 };
22
+ for (int i = 0 ; i < m; i++)
23
+ {
24
+ ct[txt[i]]++;
25
+ cp[pat[i]]++;
26
+ }
27
+ if (m == n)
28
+ return isSame (ct, cp);
29
+ for (int i = m; i < n; i++)
30
+ {
31
+ if (isSame (ct, cp))
32
+ return true ;
33
+ ct[txt[i]]++;
34
+ ct[txt[i - m]]--;
35
+ }
36
+ return false ;
37
+ }
38
+
39
+ int main ()
40
+ {
41
+ string s, k;
42
+ cin >> s >> k;
43
+ cout << anagramSeach (s, k);
44
+ return 0 ;
45
+ }
Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ using namespace std ;
3
+
4
+ bool areRotated (string s1, string s2)
5
+ {
6
+ if (s1.length () != s2.length ())
7
+ return false ;
8
+ return (s1 + s1).find (s2) != string::npos;
9
+ }
10
+
11
+ int main ()
12
+ {
13
+ string s1, s2;
14
+ cin >> s1 >> s2;
15
+ cout << areRotated (s1, s2);
16
+ return 0 ;
17
+ }
You can’t perform that action at this time.
0 commit comments