题解 | #单词倒排#

单词倒排

https://www.nowcoder.com/practice/81544a4989df4109b33c2d65037c5836?tpId=37&tags=&title=&difficulty=0&judgeStatus=0&rp=1&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26tpId%3D37%26type%3D37

/*
与 HJ12 和 HJ13类似。
    本题比前面的多了 判断字符是否是字母的操作
*/

#include <algorithm>
#include <cctype>
#include <iostream>
using namespace std;

string reverseStr(string str) {
    int len = str.length();
    string ans;
    // 非字母用空格代替
    for(auto c : str){
    if( isalpha(c) ){
            ans.append(1, c);
        }else{
            ans.append(1, ' ');
        }
    }

    reverse(ans.begin(), ans.end());

    len = ans.length();
    for (int i = 0; i < len; ++i) {
        int j = i;
        while (ans[j] != ' ' && j < len) {
            j++;
        }
        reverse(ans.begin() + i, ans.begin() + j);
        i = j;
    }

    return ans;
}

int main() {
    string str;
    getline(cin, str);

    cout << reverseStr(str) << endl;

    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论
挺好
点赞 回复 分享
发布于 2024-10-10 09:35 浙江

相关推荐

评论
1
1
分享

创作者周榜

更多
牛客网
牛客企业服务