/
091_ReverseWordsInSentence.cpp
123 lines (100 loc) · 2.02 KB
/
091_ReverseWordsInSentence.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
// Coding Interviews: Questions, Analysis & Solutions
// Harry He
#include <stdio.h>
#include <string>
void Reverse(char *pBegin, char *pEnd)
{
if(pBegin == NULL || pEnd == NULL)
return;
while(pBegin < pEnd)
{
char temp = *pBegin;
*pBegin = *pEnd;
*pEnd = temp;
pBegin ++, pEnd --;
}
}
char* ReverseSentence(char *pData)
{
if(pData == NULL)
return NULL;
char *pBegin = pData;
char *pEnd = pData;
while(*pEnd != '\0')
pEnd ++;
pEnd--;
// Reverse the whole sentence
Reverse(pBegin, pEnd);
// Reverse every word in the sentence
pBegin = pEnd = pData;
while(*pBegin != '\0')
{
if(*pBegin == ' ')
{
pBegin ++;
pEnd ++;
}
else if(*pEnd == ' ' || *pEnd == '\0')
{
Reverse(pBegin, --pEnd);
pBegin = ++pEnd;
}
else
{
pEnd ++;
}
}
return pData;
}
// ==================== Test Code ====================
void Test(char* testName, char* input, char* expectedResult)
{
if(testName != NULL)
printf("%s begins: ", testName);
ReverseSentence(input);
if((input == NULL && expectedResult == NULL)
|| (input != NULL && strcmp(input, expectedResult) == 0))
printf("Passed.\n\n");
else
printf("Failed.\n\n");
}
// Multiple words
void Test1()
{
char input[] = "I am a student.";
char expected[] = "student. a am I";
Test("Test1", input, expected);
}
// Only one word
void Test2()
{
char input[] = "Wonderful";
char expected[] = "Wonderful";
Test("Test2", input, expected);
}
// Null pointer
void Test3()
{
Test("Test3", NULL, NULL);
}
// empty string
void Test4()
{
Test("Test4", "", "");
}
// Only blanks
void Test5()
{
char input[] = " ";
char expected[] = " ";
Test("Test5", input, expected);
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
return 0;
}