Prerequisites : - None
Problem : - You are given an integer N, the lines of english text with multiple words, print the text in reverse order starting from the last word of the last line and ending at the first word of the first line without printing any punctuation.
Explanation :-
Solution aims to reverse the order of words in each line while also reversing the order of lines themselves. However, we can simplify this process by using a more efficient approach.
Instead of reversing each word individually, we can store the words from each line in a data structure like a vector, and then print them in reverse order. This eliminates the need for explicitly reversing each word, reducing the overall complexity of the solution.
Here’s how we can modify the solution to achieve this:
Read the integer N from the first line, indicating the number of lines of input.
Read each line of input.
Split each line into words and store them in a data structure.
Once all lines have been read, print the stored words in reverse order, line by line.
Input each word inside the string array and then reverse the array.
Iterate over each word of the array.
Iterate over each character of the word and print the character skipping the punctuation.
C++ Solution : -
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<string> v;
string in;
while(cin >> in){
v.push_back(in);
}
reverse(v.begin(), v.end());
for(int i=0; i<v.size(); i++){
for(int j=0; j<v[i].size(); j++){
if (v[i][j] == '\'' || v[i][j] == '.' || v[i][j]==',' || v[i][j]==';' || v[i][j]==':'){
continue;
}
else {
cout << v[i][j];
}
}
cout << " ";
}
return 0;
}