HJ13 句子逆序
HJ13 句子逆序
#include#include#includeusing 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 explode(const char *sep, std::string s) { std::vector vs; int i = 0; for (; i &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& words, std::string delim) { size_t sz = 0; std::vector::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 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;}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
暂时没有评论,来抢沙发吧~