给定字符串s, 要求把s中多于一个的连续空压缩成一个空格,并将连续的非空格字符串倒序打印出来,例如,给定"abc def efg",打印"cba fed gfe"
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{ string s; getline(cin, s); for(int i = 0, j , k; i < s.size(); ++i) {
if(s[i] == ' ') {
cout << ' ';
for(j = i; j < s.size() && s[j] == ' '; ++j);
i = j - 1;
}
else {
string tmp;
for(k = i; k < s.size() && s[k] != ' '; ++k) {
tmp += s[k];
}
i = k - 1;
reverse(tmp.begin(), tmp.end());
cout << tmp;
tmp.clear();
} } return 0;
}
void reverse(string &s){
for(int i=s.size()-1;i>=0;--i){
if(s[i]==' '){
while(i>=0&&s[i--] == ' ');
cout<<' ';
}
if(s[i] == ' ')
break; cout<<s[i];
}
}
时间复杂度O(n),空间复杂度为O(1)/* 给定字符串s, 要求把s中多于一个的连续空压缩成一个空格,并将连续的非空格字符串倒序打印出来,
* 例如,给定"abc def efg",打印"cba fed gfe"
*/
#include <algorithm>
#include <iostream>
#include <string>
int main() {
std::string s;
std::getline(std::cin, s);
auto NextSpace = std::find(s.begin(), s.end(), (const char)' ');
auto NextNotSpace = std::find_if_not(s.begin(), s.end(), [](const char &sc) {
return sc == ' ' ? true : false;
});
std::string Output;
if (NextSpace == s.begin()) {
Output.push_back(' ');
}
while (NextSpace != s.end() && NextNotSpace != s.end()) {
NextSpace = std::find(NextNotSpace, s.end(), (const char)' ');
for (auto i = NextSpace - 1; i >= NextNotSpace; --i) {
Output.push_back(*i);
}
NextNotSpace = std::find_if_not(NextSpace, s.end(), [](const char &sc) {
return sc == ' ' ? true : false;
});
Output.push_back(' ');
}
std::cout << Output << std::endl;
return 0;
} VS 2017 会报异常但是 g++ 不会,很神奇
void solution(string s) {
string tmp("");
stack<char> sta;
bool change = false;
int len = (int)s.length();
for (int i = 0; i < len; i++) {
while (s[i] == ' ' && i < len) {
change = true;
i++;
}
if (change) {
tmp.push_back(' ');
change = false;
while (!sta.empty()) {
cout << sta.top();
sta.pop();
}
cout << " ";
}
if (i < len) {
tmp.push_back(s[i]);
sta.push(s[i]);
}
}
cout << endl;
}