Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 142637c

Browse files
Create Reverse Words in a String
1 parent c3e3ea5 commit 142637c

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
想法:將所有字串擷取出來,存在 stack 裡面;接著再從頂部 pop 出並組成新字串即可
2+
3+
Time Complexity : O(n) for traversing string s
4+
Space Complexity : O(n) for the stack to store all strings (the strings total length <= s.length )
5+
6+
class Solution {
7+
public:
8+
string reverseWords(string s) {
9+
stack<string> store ;
10+
string temp ;
11+
for(auto &i : s) {
12+
if ( i == ' ' ) {
13+
if ( !temp.empty() ) {
14+
store.push(temp) ;
15+
temp = "";
16+
}
17+
}
18+
else
19+
temp += i ;
20+
}
21+
if (!temp.empty())
22+
store.push(temp);
23+
24+
string ans ;
25+
while ( !store.empty() ) {
26+
if ( ans.empty() ) {
27+
ans += store.top() ;
28+
}
29+
else {
30+
ans += " " + store.top() ;
31+
}
32+
store.pop() ;
33+
}
34+
return ans ;
35+
}
36+
};
37+
38+
// 法二:如果不使用額外空間(除了輸出字串),就要把 stack 的過程直接作用在輸出字串上
39+
也就是 ans = temp + " " + ans
40+
41+
Time Complexity : O(n^2) for O(n) strings and each one take O(n) time to concate
42+
Space Complexity : O(n) for the answer string
43+
44+
45+
class Solution {
46+
public:
47+
string reverseWords(string s) {
48+
stack<string> store ;
49+
string temp ;
50+
for(auto &i : s) {
51+
if ( i == ' ' ) {
52+
if ( !temp.empty() ) {
53+
store.push(temp) ;
54+
temp = "";
55+
}
56+
}
57+
else
58+
temp += i ;
59+
}
60+
if (!temp.empty())
61+
store.push(temp);
62+
63+
string ans ;
64+
while ( !store.empty() ) {
65+
if ( ans.empty() ) {
66+
ans += store.top() ;
67+
}
68+
else {
69+
ans += " " + store.top() ;
70+
}
71+
store.pop() ;
72+
}
73+
return ans ;
74+
}
75+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /