-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathReverseWordsInSentence.cpp
71 lines (71 loc) · 1.44 KB
/
ReverseWordsInSentence.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
// Solution 1:
class Solution {
public:
string ReverseSentence(string s) {
string res="";
int n = s.size();
if (n==0)
return res;
if (n==1)
return s;
for (int i=n,j=n-1;j>=0;j--)
{
if (s[j]==' ')
{
for(int k=j+1;k<i;k++)
{
res+=s[k];
}
res += s[j];
i=j;
}
if (j==0 && res!="")
{
for (int x=j;x<i;x++)
{
res+=s[x];
}
}
if (j==0 && res=="")
{
res = s;
}
}
return res;
}
};
// Solution 2:
class Solution {
public:
void Reverse(string &s, int start,int end)
{
while(start<end)
{
swap(s[start],s[end]);
start++;
end--;
}
}
string ReverseSentence(string s)
{
string res;
int n = s.size();
// 整体翻转整个句子
Reverse(s,0,n-1);
int i=0;
int start = 0;
int end = 0;
while(i<n)
{
while(i<n && s[i]==' ') i++;
start = end = i;
while(i<n && s[i]!=' ')
{
i++;
end++;
}
Reverse(s,start,end-1);
}
return s;
}
};