AcWing 77. 翻转单词顺序

习题地址 https://www.acwing.com/problem/content/description/73/

题目描述
输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。

为简单起见,标点符号和普通字母一样处理。

例如输入字符串”I am a student.”,则输出”student. a am I”。

样例

输入:"I am a student."

输出:"student. a am I"

算法1
除开先翻转整个句子 再反转单词的做法 我的比较硬核 直接逐个双指针的翻转整个单词

代码

class Solution {
public:
int findsubString(const string& s, string& revertStr ,size_t& findPos) {
    size_t start = s.find_last_not_of(' ', findPos);
    if (start == string::npos) {
        return -1;
    }
    findPos = start ;
    size_t end = s.find_last_of(' ', findPos);

    findPos = end; int len = 0;
    if (end == string::npos){
        end = 0;
        len = start - end + 1;
    }
    else{
        end++;
        len = start - end+1;
    }
    revertStr += s.substr(end, len);
    if (findPos == string::npos)
        return -1;
    revertStr += " ";

    return 1;
}


string reverseWords(string s) {
    if (s.empty()) return s;
    string res;
    size_t findPos = s.size()-1;
    int ret = findsubString(s, res, findPos);

    while (ret == 1) {
        ret = findsubString(s, res, findPos);
    }

    return res;
}

};

作者:defddr
链接:https://www.acwing.com/solution/acwing/content/2907/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
阿里打赏 微信打赏
原文地址:https://www.cnblogs.com/itdef/p/11207306.html