HJ 31 [Intermediate] Words inverted

Ideas:

Traverse from the end of the string to the front, push the alpha into the stack, and skip the non-alpha.

Title description

Invert all words in the string.

Description:

1. There are only 26 uppercase or lowercase English letters in the characters that make up a word;

2. Characters that do not form a word are regarded as word spacers;

3. The inverted word spacer is required to be represented by a single space; if there are multiple spacers between adjacent words in the original string, only one space spacer is allowed after the inverted conversion;

4. The maximum length of each word is 20 letters;

Example:

#include<iostream>
#include<vector>
#include<cstring>
using namespace std;

int main()
{
    vector<char> word;
    char str[10000];
    cin.getline(str, 10000);
    bool first = true;
    int i = strlen(str)-1;
    while(i >= 0) {
        while(i >= 0 && isalpha(str[i])) {
            word.push_back(str[i]);
            --i;
        }
        while(i >= 0 && !isalpha(str[i])) {
            --i;
        }
        if(word.size() > 0) {
            if(first) first = false;
            else cout << ' ';
        }
        while(word.size() > 0) {
            char ch = word.back();
            word.pop_back();
            cout << ch;
        }
    }
}

 

Guess you like

Origin blog.csdn.net/u012571715/article/details/115000724