-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path151.cpp
More file actions
59 lines (55 loc) · 1.31 KB
/
151.cpp
File metadata and controls
59 lines (55 loc) · 1.31 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
//
// 151.cpp
// LeetCode
//
// Created by 张佐玮 on 15/5/18.
// Copyright (c) 2015年 JarvisZhang. All rights reserved.
//
// Title: Reverse Words in a String
//
#include <iostream>
using namespace std;
class Solution {
public:
void reverseWords(string &s) {
int rear = (int) s.length() - 1;
string result;
while (rear >= 0) {
if (s[rear] != ' ') {
int front = rear;
while (front >= 0 && s[--front] != ' ') ;
for (int i = front + 1; i <= rear; i++) {
result.push_back(s[i]);
}
result.push_back(' ');
rear = front;
}
else {
rear--;
}
}
s = result.substr(0, result.length() - 1);
}
};
class Test {
private:
static void runTest(string &s) {
Solution solution;
cout << "\"" << s << "\"" << " -> ";
solution.reverseWords(s);
cout << "\"" << s << "\"" << endl;
}
public:
void sample() {
string s1("the sky is blue");
string s2(" ");
string s3("");
string s4(" hello world ");
string s5("hello");
runTest(s1);
runTest(s2);
runTest(s3);
runTest(s4);
runTest(s5);
}
};