练习:反转单词顺序
代码1:
#include <iostream>
#include <stack>
#include <string>
#include <algorithm>
using namespace std;
void func(string str1, string& str2) {
if(str1.size() <= 1) str2 = str1;
string temp;
stack<string> st;
for(int i = 0;i < str1.size();i++) {
if(str1[i] == ' ' && temp.empty() == false) {
st.push(temp);
temp.clear();
}
if(str1[i] != ' '){
temp.push_back(str1[i]);
}
if(i == str1.size()-1 && temp.empty() == false) {
st.push(temp);
temp.clear();
}
}
while(!st.empty()) {
str2.append(st.top());
st.pop();
if(!st.empty()) {
str2.append(" ");
}
}
}
int main() {
string str1 = "Hello world! sldkf sdkf";
string str2;
func(str1, str2);
cout << str2 << endl;
return 0;
}
代码(2018年9月2日)
#include <iostream>
#include <vector>
#include <string>
#include <stack>
using namespace std;
void func(const string& str, string& res) {
res.clear();
if (str.empty()) return;
stack<string> st;
int i = 0;
while(i < str.size()) {
while(i < str.size() && str[i] == ' ') i++;
int h1 = i;
while(i < str.size() && str[i] != ' ') i++;
int h2 = i;
string tmp(str.begin()+h1, str.begin()+h2);
st.push(tmp);
}
while(!st.empty()) {
res += (st.top());
st.pop();
if(!st.empty()) res += " ";
}
}
int main() {
string str, res;
while(getline(cin, str)) {
func(str, res);
cout << res << endl;
}
return 0;
}
代码2:
#include <iostream>
#include <vector>
#include <string>
#include <stack>
using namespace std;
void func(const string& str, string& res) {
res.clear();
if (str.empty()) return;
stack<string> st;
int h1 = 0, h2 = 0;
do {
while(h1 < str.size() && str[h1] == ' ') h1++;
h2 = h1;
while(h2 < str.size() && str[h2] != ' ') h2++;
string tmp(str.begin()+h1, str.begin()+h2);
st.push(tmp);
h1 = h2;
} while(h1 < str.size());
while(!st.empty()) {
res += (st.top());
if (st.size() > 1) res += (" ");
st.pop();
}
}
int main() {
string str, res;
while(getline(cin, str)) {
func(str, res);
cout << res << endl;
}
return 0;
}
代码:
class Solution {
public:
string ReverseSentence(string str) {
int len = str.size();
if(len == 0) return str;
stack<string> st;
int i = 0,j = 0;
string temp;
while(j < len) {
while(j < len && str[j] != ' ') {
temp.push_back(str[j++]);
}
if(temp.size() != 0) {
st.push(temp);
temp.clear();
i = 0;
}
while(j < len && str[j] == ' ') j++;
}
if(st.empty()) return str;
string res;
while(!st.empty()) {
res += st.top();
res += " ";
st.pop();
}
res.pop_back();
return res;
}
};
代码:
class Solution {
public:
string ReverseSentence(string str) {
int len = str.size();
if(len == 0) return str;
typedef string::iterator Iter;
string tem = " ";
Iter t1 = tem.begin(), t2 = tem.end();
stack<string> st;
Iter iter1 = str.begin(), iter2 = str.begin();
while((iter2 = find_first_of(iter1, str.end(), t1, t2)) != str.end()
|| iter1 != iter2) {
if(iter1 != iter2) {
string temp(iter1, iter2);
st.push(temp);
}
if(iter2 == str.end()) break;
++iter2;
iter1 = iter2;
}
if(st.empty()) {
return str;
}
string res;
while(!st.empty()) {
res += st.top();
res += " ";
st.pop();
}
res.pop_back();
return res;
}
};