forked from lennylxx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
151.c
63 lines (58 loc) · 1.25 KB
/
151.c
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void reverseWords(char *s) {
int len = strlen(s);
int i, j;
// remove the redundant spaces
i = j = 0;
while (i < len)
{
while (s[i] == ' ') {
i++;
}
if (i >= len) break;
while (s[i] != ' ' && s[i] != '\0') {
s[j] = s[i];
j++;
i++;
}
s[j] = ' ';
j++;
i++;
}
if (j > 0) j--;
s[j] = '\0';
// reverse the whole string
int new_len = strlen(s);
char t;
for (i = 0; i < new_len / 2; i++)
{
t = s[i];
s[i] = s[new_len - 1 - i];
s[new_len - 1 - i] = t;
}
// reverse the word separately
int a, b;
a = b = j = 0;
for (i = 0; i < new_len + 1; i++)
{
if (s[i] == ' ' || s[i] == '\0')
{
b = i - 1;
for (j = a; j < (b - a + 1) / 2 + a; j++){
t = s[j];
s[j] = s[b + a - j];
s[b + a - j] = t;
}
a = i + 1;
}
}
}
int main()
{
char s[] = " the sky is blue ";
reverseWords(s);
printf("%s\n", s);
return 0;
}