forked from MainakRepositor/500-CPP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
182.cpp
92 lines (77 loc) · 1.96 KB
/
182.cpp
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// A C++ program to remove "b" and 'ac' from input string
#include <iostream>
using namespace std;
#define ONE 1
#define TWO 2
// The main function that removes occurrences of "a" and "bc"
// in input string
void stringFilter(char *str)
{
// state is initially ONE (The previous character is not a)
int state = ONE;
// i and j are index variables, i is used to read next
// character of input string, j is used for indexes of output
// string (modified input string)
int j = 0;
// Process all characters of input string one by one
for (int i = 0; str[i] != '\0'; i++)
{
/* If state is ONE, then do NOT copy the current character
to output if one of the following conditions is true
...a) Current character is 'b' (We need to remove 'b')
...b) Current character is 'a' (Next character may be 'c') */
if (state == ONE && str[i] != 'a' && str[i] != 'b')
{
str[j] = str[i];
j++;
}
// If state is TWO and current character is not 'c' (other-
// wise we ignore both previous and current characters)
if (state == TWO && str[i] != 'c')
{
// First copy the previous 'a'
str[j] = 'a';
j++;
// Then copy the current character if it is not 'a'
// and 'b'
if (str[i] != 'a' && str[i] != 'b')
{
str[j] = str[i];
j++;
}
}
// Change state according to current character
state = (str[i] == 'a')? TWO: ONE;
}
// If last character was 'a', copy it to output
if (state == TWO)
{
str[j] = 'a';
j++;
}
// Set the string terminator
str[j] = '\0';
}
/* Driver program to check above functions */
int main()
{
char str1[] = "ad";
stringFilter(str1);
cout << str1 << endl;
char str2[] = "acbac";
stringFilter(str2);
cout << str2 << endl;
char str3[] = "aaac";
stringFilter(str3);
cout << str3 << endl;
char str4[] = "react";
stringFilter(str4);
cout << str4 << endl;
char str5[] = "aa";
stringFilter(str5);
cout << str5 << endl;
char str6[] = "ababaac";
stringFilter(str6);
cout << str6 << endl;
return 0;
}