-
Notifications
You must be signed in to change notification settings - Fork 160
/
Copy pathDeleteAdoubleB.cpp
71 lines (53 loc) · 1.32 KB
/
DeleteAdoubleB.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
/*
Given a string£¬delete all char A£¬and double all char B.
For example:
Input: ACAABDB
Output: CBBDBB
*/
/*
solution: scan first time from the beginning to remove all 'A' and count the number of B, scan second time from the end to double B.
O(n) time, O(1) space
*/
#include<iostream>
using namespace std;
char *StringRemoveADoubleB(char *str) {
if (!str) return NULL;
char *orgiter = str;
char *newiter = orgiter;
int countb = 0;
int len = 0;
while (*orgiter) {
if (*orgiter == 'B') countb++; // Count B
if (*orgiter != 'A') {
*newiter++= *orgiter++;
len++;
} else {
orgiter++; // Remove A
}
}
if (len) {
orgiter = str+(len+countb); //new string length
*orgiter = '\0';
orgiter--;
newiter--;
while (newiter != str) {
if (*newiter == 'B') {
*orgiter-- = 'B';
}
*orgiter-- = *newiter--;
}
if (*newiter == 'B') { //the begin of str is B
*orgiter = 'B';
}
}
return str;
}
int main() {
char *str1 = "CAABD";
char *str2 = "ACAABDB";
char *str3 = "BACAABDBA";
cout<<StringRemoveADoubleB(str1)<<endl;
cout<<StringRemoveADoubleB(str2)<<endl;
cout<<StringRemoveADoubleB(str3)<<endl;
return 0;
}