HJ13 句子逆序 #includeiostream #includecstring #includevector using namespace std ; class Solution { private : static bool charInStr ( char c , const char * sep ) { bool b = false ; for ( int i = 0 ; sep [ i ] != '\0' ; i ++
HJ13 句子逆序
#include<iostream>#include<cstring>
#include<vector>
using namespace std;
class Solution {
private:
static bool charInStr(char c, const char *sep) {
bool b = false;
for (int i = 0; sep[i] != '\0'; i++) {
if (c == sep[i]) {
b = true;
break;
}
}
return b;
}
std::vector<std::string> explode(const char *sep, std::string s) {
std::vector<std::string> vs;
int i = 0;
for (; i <s.size(); i++) {
if (false == charInStr(s[i], sep)) {
break;
}
}
int j = i;
for (; i < s.size(); i++) {
if (j < i && charInStr(s[i], sep)) {
vs.push_back(s.substr(j, i-j));
j = i+1;
}
}
if (j < i) {
vs.push_back(s.substr(j, i-j));
}
return vs;
}
static void reverse(std::vector<std::string> &vs) {
std::string word;
for (int i = 0, j = vs.size()-1; i < j; i++, j--) {
word = vs[i];
vs[i] = vs[j];
vs[j] = word;
}
}
static char *join(const std::vector<std::string>& words, std::string delim) {
size_t sz = 0;
std::vector<std::string>::const_iterator it;
for (it = words.begin(); it != words.end(); ++it) {
sz += it->size();
}
sz += delim.size() * (words.size()-1);
sz += 1;
char *ans = (char *)malloc(sizeof(char) * sz);
char *p = ans;
it = words.begin();
::strncpy(ans, it->c_str(), it->size());
p += it->size();
++it;
for (; it != words.end(); ++it) {
::strncpy(p, delim.c_str(), delim.size());
p += delim.size();
::strncpy(p, it->c_str(), it->size());
p += it->size();
}
return ans;
}
public:
char *reverseWords(std::string line) {
std::vector<std::string> words = explode(" \t\r\n", std::move(line));
reverse(words);
// for (auto w : words) {
// std::cout << w << std::endl;
// }
return join(words, " ");
}
};
int main(){
char line[1000] = {'\0'};
std::cin.getline(line, 1000);
// strcpy(line, "I am a boy");
Solution s;
char *ans = s.reverseWords(std::string(line));
std::cout << ans << std::endl;
free(ans);
return 0;
}