Rearrange Words in a Sentence in C++

C++Server Side ProgrammingProgramming

Suppose we have a string with different words, that string is called sentence, and this is in the following format −

  • First letter is in upper case.

  • Each word in text are separated by a single space character.

We have to rearrange the words in text such that all words are rearranged in increasing order of their lengths. If two words have the same length, arrange them in their original order.

Then finally return the string by applying these rules.

So, if the input is like "I love to code in cpp", then the output will be "I to in cpp love code"

To solve this, we will follow these steps −

  • make the first character of text into small letter

  • Define an array x := put all words after splitting text using space

  • Define an array s of pairs

  • for initialize i := 0, when i < size of x, update (increase i by 1), do −

    • insert {x[i],i} at the end of s

  • sort the array s based on length, if lengths are same use index values

  • ret := empty string

  • for initialize i := 0, when i < size of s, update (increase i by 1), do −

    • ret := ret concatenate first element of s[i]

    • if i is not equal to size of s, then −

      • ret := ret concatenate with blank space

  • make first character of ret to capital

  • return ret

Example 

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   vector <string> split(string& s, char delimiter){
      vector <string> tokens;
      string token;
      istringstream tokenStream(s);
      while(getline(tokenStream, token, delimiter)){
         tokens.push_back(token);
      }
      return tokens;
   }
   static bool cmp(pair <string, int>& a, pair <string, int>& b){
      if(a.first.size() != b.first.size()) return a.first.size() < b.first.size();
         return a.second < b.second;
   }
   static bool a(string& a, string& b){
      return a.size() < b.size();
   }
   string arrangeWords(string text) {
      text[0] += 'a' - 'A';
      vector<string> x = split(text, ' ');
      vector<pair<string, int> > s;
      for (int i = 0; i < x.size(); i++)
      s.push_back({ x[i], i });
      sort(s.begin(), s.end(), cmp);
      string ret = "";
      for (int i = 0; i < s.size(); i++) {
         ret += s[i].first;
         if (i != s.size() - 1)
            ret += ' ';
      }
      ret[0] += 'A' - 'a';
      return ret;
   }
};
main(){
   Solution ob;
   cout << (ob.arrangeWords("I love to code in cpp"));
}

Input

"I love to code in cpp"

Output

I to in cpp love code
raja
Published on 17-Nov-2020 12:30:04
Advertisements