Skip to content

Commit 01abdeb

Browse files
Merge pull request #228 from shafa45/main
problems on strings
2 parents fe86e70 + a91dc7f commit 01abdeb

File tree

3 files changed

+131
-0
lines changed

3 files changed

+131
-0
lines changed

String/KMPalgo.cpp

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
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+
}

String/angramSearch.cpp

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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+
}

String/areRotation.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
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+
}

0 commit comments

Comments
 (0)