-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
reverseWordsInAString.II.cpp
64 lines (53 loc) · 1.46 KB
/
reverseWordsInAString.II.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
// Source : https://oj.leetcode.com/problems/reverse-words-in-a-string-ii/
// Author : Hao Chen
// Date : 2015-02-09
/**********************************************************************************
*
* Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
*
* The input string does not contain leading or trailing spaces and the words are always separated by a single space.
*
* For example,
* Given s = "the sky is blue",
* return "blue is sky the".
*
* Could you do it in-place without allocating extra space?
*
*
**********************************************************************************/
#include <ctype.h>
#include <iostream>
#include <string>
using namespace std;
void swap(char &a, char &b) {
char temp = a;
a = b;
b = temp;
}
void reverse(string &s, int begin, int end) {
while(begin < end) {
swap(s[begin++], s[end--]);
}
}
void reverseWords(string &s) {
if (s.size()<=1) return;
// reverse the whole string
reverse(s, 0, s.size()-1);
// reverse the each word
for ( int begin=0, i=0; i<=s.size(); i++ ) {
if ( isblank(s[i]) || s[i] == '\0') {
reverse(s, begin, i-1);
begin = i+1;
}
}
}
int main(int argc, char** argv)
{
string s = "the sky is blue";
if ( argc > 1 ) {
s = argv[1];
}
cout << s << endl;
reverseWords(s);
cout << s << endl;
}