Efficiently reverse the order of the words (not characters) in an array of characters

前端 未结 21 1982
[愿得一人]
[愿得一人] 2020-11-28 04:40

Given an array of characters which forms a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.

Example input and

21条回答
  •  广开言路
    2020-11-28 04:49

    A C++ solution:

    #include 
    #include 
    using namespace std;
    
    string revwords(string in) {
        string rev;
        int wordlen = 0;
        for (int i = in.length(); i >= 0; --i) {
            if (i == 0 || iswspace(in[i-1])) {
                if (wordlen) {
                    for (int j = i; wordlen--; )
                        rev.push_back(in[j++]);
                    wordlen = 0;
                }
                if (i > 0)
                    rev.push_back(in[i-1]);
            }
            else
                ++wordlen;
        }
        return rev;
    }
    
    int main() {
        cout << revwords("this is a sentence") << "." << endl;
        cout << revwords("  a sentence   with extra    spaces   ") << "." << endl;
        return 0;
    }
    

提交回复
热议问题