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

前端 未结 21 1956
[愿得一人]
[愿得一人] 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:44

    #include 
    #include 
    
    void reverse(std::string& foo) {
        using namespace std;
        std::reverse(foo.begin(), foo.end());
        string::iterator begin = foo.begin();
        while (1) {
            string::iterator space = find(begin, foo.end(), ' ');
            std::reverse(begin, space);
            begin = boost::next(space);
            if (space == foo.end())
                break;
        }
    }
    

提交回复
热议问题