-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path151.c
More file actions
68 lines (58 loc) · 1.4 KB
/
151.c
File metadata and controls
68 lines (58 loc) · 1.4 KB
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
/*
* Process the string s such that:
* 1) the first character is not a space
* 2) the last character is not a space
* 3) No two spaces are next to each other
* Finally, return the length of the "skipped string"
*/
int skip_spaces(char *s) {
int i = 0;
int j = 0;
// invariant: j <= i
// skip leading spaces
while ((s[i] != '\0') && (s[i] == ' ')) i++;
while (s[i] != '\0') {
if (s[i] != ' ') {
s[j++] = s[i++];
}
else {
s[j++] = ' ';
while ((s[i] != '\0') && s[i] == ' ') {
i++;
}
}
}
while (j > 0 && s[j - 1] == ' ') j--;
s[j] = '\0';
return j;
} /* skip_spaces() */
/*
* Modify s such that the substring [l, r] appears in reverse order.
*/
void reverse_range(char *s, int l, int r) {
// temporary variable
char t = '\0';
while (l < r) {
// swap s[l] and s[r]
t = s[l];
s[l] = s[r];
s[r] = t;
l++;
r--;
}
} /* reverse_range() */
char* reverseWords(char* s) {
int length = skip_spaces(s);
reverse_range(s, 0, length - 1);
int start = 0;
int end = 0;
while (end <= length) {
// detected word at [start, end)
if ((end == length) || (s[end] == ' ')) {
reverse_range(s, start, end - 1);
start = end + 1;
}
end++;
}
return s;
}