-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreverse-words-in-a-string-iii.cpp
102 lines (87 loc) · 1.42 KB
/
reverse-words-in-a-string-iii.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// https://leetcode.com/problems/reverse-words-in-a-string-iii/
// Naive Approach
class Solution
{
public:
string reverseWords(string s)
{
int strLength = s.size();
int leftPointer = 0;
int rightPointer = 0;
int i = 0, j = 0;
while (leftPointer < strLength)
{
while ((s[rightPointer] != ' ') && (rightPointer < strLength))
{
rightPointer++;
}
i = leftPointer;
j = rightPointer - 1;
leftPointer = rightPointer + 1;
rightPointer = leftPointer;
// reverse(s.begin() + i, s.begin() + j+1);
while (i < j)
{
swap(s[i], s[j]);
i++;
j--;
}
}
return s;
}
};
// Using Stack
class Solution
{
public:
string reverseWords(string s)
{
int strLength = s.size();
string result = "";
string temp = "";
stack<char> st;
for (int i = 0; i < strLength; ++i)
{
if (s[i] != ' ')
{
st.push(s[i]);
}
else
{
while (st.empty() == false)
{
temp = st.top();
result.append(temp);
st.pop();
}
result.append(" ");
}
}
while (st.empty() == false)
{
temp = st.top();
result.append(temp);
st.pop();
}
return result;
}
};
// Using Stringstream
class Solution
{
public:
string reverseWords(string s)
{
stringstream ss(s);
string word = "";
string result = "";
while (ss >> word)
{
reverse(word.begin(), word.end());
result.append(word);
result.append(" ");
}
result.pop_back();
return result;
}
};