-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
replace_pi.cpp
60 lines (55 loc) · 1.16 KB
/
replace_pi.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
/* Problem statement:
You are given a string, you have to replace all the occurrences of "pi" int the string into 3.14. */
#include <bits/stdc++.h>
using namespace std;
void replacepi(char a[], int i)
{
if (a[i] == '\0' or a[i + 1] == '\0')
{
return;
}
//checks if the current and the next part of the string is "pi"
if (a[i] == 'p' and a[i + 1] == 'i')
{
//Shifting the replacement of 3.14
int j = i + 2;
//taking j to the end of the string
while (a[j] != '\0')
{
j++;
}
while (j >= i + 2)
{
a[j + 2] = a[j];
j--;
}
//replacing "pi" with 3.14
a[i] = '3';
a[i + 1] = '.';
a[i + 2] = '1';
a[i + 3] = '4';
replacepi(a, i + 4);
}
//Go to the next position
else
{
replacepi(a, i + 1);
}
}
//Time Complexity :O(n)
int main()
{
char a[1000];
cin >> a;
replacepi(a, 0);
cout << a << endl;
return 0;
}
/*
Example 1:
Input : xpighpilmpipi
Output: x3.14gh3.14lm3.143.14
Example 2:
Input : abcpipikjpilk
Output: abc3.143.14kj3.14lk
Time Complexity :O(n) */