Skip to content

Commit 70158f2

Browse files
authored
Merge pull request #193 from pranavpatel3012/master
Added leetcode problem "Reverse Words in a String" in c++ with optimized solution --151.cpp
2 parents d68994b + f59d5a8 commit 70158f2

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

leetcode/cpp/string/151.cpp

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class Solution
2+
{
3+
public:
4+
string reverseWords(string a)
5+
{
6+
int i = 0, n;
7+
string st = "";
8+
vector<string> wd;
9+
for (i = a.length() - 1; i >= 0; i--)
10+
{
11+
if (a[i] != ' ')
12+
{
13+
break;
14+
}
15+
}
16+
n = i + 1;
17+
for (i = 0; i < n; i++)
18+
{
19+
if (a[i] != ' ')
20+
{
21+
break;
22+
}
23+
}
24+
for (; i < n; i++)
25+
{
26+
if (a[i] == ' ')
27+
{
28+
if (a[i - 1] != ' ')
29+
{
30+
wd.push_back(st);
31+
st = "";
32+
}
33+
}
34+
else
35+
{
36+
st += a[i];
37+
}
38+
}
39+
wd.push_back(st);
40+
st = "";
41+
for (i = wd.size() - 1; i >= 0; i--)
42+
{
43+
st += wd[i];
44+
if (i != 0)
45+
{
46+
st += " ";
47+
}
48+
}
49+
return st;
50+
}
51+
};

0 commit comments

Comments
 (0)