-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadap1.cpp
More file actions
65 lines (50 loc) · 1.44 KB
/
adap1.cpp
File metadata and controls
65 lines (50 loc) · 1.44 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
60
61
62
63
64
65
#include <iostream>
#include <string.h>
/**
* Program to remove occurrences of pat in str
* This is using no space except for look up table and linear time algorithm
*/
int main()
{
char *str = strdup("membermememeererermemberamemberp");
char *pat = strdup("ermb");
std::cout << "str: " << str << " pat: " << pat << std::endl;
bool lookup[26];
memset(lookup, false, 26);
for(int i=0; i<strlen(pat); i++)
lookup[pat[i]-'a'] = true;
int m=0, n=0;
// m - first pattern character
// n - first non pattern character
// both updated for every iteration
while(true)
{
for(int i=m; i<strlen(str); i++)
{
if(!lookup[str[i]-'a'])
m++;
else
break;
}
// start the stride after first character in pattern
n=m;
for(int i=n; i<strlen(str); i++)
{
if(lookup[str[i]-'a'])
n++;
else
break;
}
//std::cout << "m " << m << std::endl;
//std::cout << "n " << n << std::endl;
if(n >= strlen(str)) break;
// swap
char t = str[m];
str[m] = str[n];
str[n] = t;
m++;
// std::cout << "after swap: str: " << str << " pat: " << pat << std::endl;
}
str[m] = '\0';
std::cout << "at the end - str: " << str << " pat: " << pat << std::endl;
}