forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverseWordsInAString.cpp
88 lines (76 loc) · 2.04 KB
/
reverseWordsInAString.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
// Source : https://oj.leetcode.com/problems/reverse-words-in-a-string/
// Author : Hao Chen
// Date : 2014-06-16
/**********************************************************************************
*
* Given an input string, reverse the string word by word.
*
* For example,
* Given s = "the sky is blue",
* return "blue is sky the".
*
*
* Clarification:
*
* What constitutes a word?
* A sequence of non-space characters constitutes a word.
* Could the input string contain leading or trailing spaces?
* Yes. However, your reversed string should not contain leading or trailing spaces.
* How about multiple spaces between two words?
* Reduce them to a single space in the reversed string.
*
*
**********************************************************************************/
#include <ctype.h>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void reverseWords(string &s) {
bool wordStart = false;
vector<string> v;
const char *pHead =s.c_str();
const char *pStr, *pBegin, *pEnd;
for (pStr=pHead; *pStr!='\0'; pStr++) {
if (!isspace(*pStr) && wordStart == false){
wordStart = true;
pBegin = pStr;
continue;
}
if(isspace(*pStr) && wordStart==true){
wordStart=false;
pEnd = pStr;
v.insert(v.begin(), s.substr(pBegin-pHead, pEnd-pBegin) );
}
}
if (wordStart==true){
pEnd = pStr;
v.insert(v.begin(), s.substr(pBegin-pHead, pEnd-pBegin) );
}
if (v.size()>0){
s.clear();
char space=' ';
vector<string>::iterator it;
for (it=v.begin(); it!=v.end(); ++it) {
s = s + *it;
s.push_back(space);
}
s.erase(s.end()-1);
}else{
s.clear();
}
cout << "[" << s << "]" <<endl;
}
main()
{
string s;
reverseWords(s);
s=" ";
reverseWords(s);
s="1 ";
reverseWords(s);
s="love";
reverseWords(s);
s="i love cpp";
reverseWords(s);
}